In this tutorial you will learn:
- String indexing and slicing
- How to count the number of characters using len()
- String operations
- Some useful string methods
1 String indexing and slicing:
In the prevous tutorial (Python Data Types Part Two), we have seen how to access any character in a string using indexing method:
0var = "Hello World"
1
2#OUTPUT: H o
3print(var[0], var[4])
Python has a very powerfull feature that let you slice any ordered sequence (string, list, tuple) called slicing.
Lets see an example:
0var = "Hello World"
1
2#OUTPUT: Hello
3print(var[0:5])
4
5#OUTPUT: Hello
6print(var[:5])
7
8#OUTPUT: World
9print(var[6:])
To use the slicing method we add two square brackets like the indexing method then we define the starting index, the index that we want to start slicing from it if we don’t define anything by default python will start from index zero ‘0’, then we add colon and the end index, which define the index where we want to stop slicing, the character at the ‘stop index’ will not be included in the sliced result the slicing will stop just before that index, if no stop index is defined python will continue to the end of the sequence.
We can also add a third number to our slicing method that allows us to set how the index of the sequence will be incremented.
Lets see an example to understand this clearly.
0var = "Hello World"
1
2#jump one character
3#OUTPUT:HloWrd
4print(var[::2])
As you see to jump one character we set the step number to two, if we type one (1) instead of two (2) we will get the whole sequence: ‘Hello World’.
So why 2 make us jump one character ? :
As you know 0 is the first index and to jump one character this means the next index after zero should be 2 because we want to jump 1 character,
now the next index after two should be 4 and the next is 6 and so on until the end of the sequence, if you notice each time we add 2 to
the previous index and this is how the number 2 in the step number means, it defines how much to add to the previous index to jump to the next index.
We can also use negative numbers for the step part:
0var = "Hello World"
1
2#OUTPUT: dlroW olleH
3print(var[::-1])
2 How to count the number of characters using len():
Python has a built-in function called len() this function take a sequence and return the length of it.
0var = "Hello World"
1
2#OUTPUT: 11
3print(len(var))
3 String Operations:
We can apply some arithmetic operators to manipulate a string object:
For example to concatenate two ore more strings objects we can use the addition ‘+’ operator:
0var1 = "Hello "
1var2 = "World"
2
3var3 = var1 + var2
4
5#OUTPUT: Hello World
6print(var3)
We can also use the multiplication operator ‘’ to multiply the string.
0var = "Hello "
1
2#OUTPUT: Hello Hello Hello
3print(var * 3)
We can also check if a sub string exists within a string or not by using the membership operator ‘in’:
0var = "Apple"
1
2#OUTPUT: True
3print('p' in var)
4
5#OUTPUT: False
6print('s' in var)
4 Some useful string methods:
In this section you learn some useful method that are part of the str object:
format:
Python str object has a method called format() that allows us to format our string.
Lets see an example:
0var1 = "abc"
1var2 = "def"
2
3#OUTPUT: var1 = abc and var2 = def
4print("var1 = {} and var2 = {}".format(var1, var2))
5
6#OUTPUT: var1 = abc and var2 = def
7print("var1 = {0} and var2 = {1}".format(var1, var2))
8
9#OUTPUT: var2 = def and var1 = abc
10print("var2 = {1} and var1 = {0}".format(var1, var2))
11
12#OUTPUT: var1 = abc and var2 = def
13print("var1 = {variable_one} and var2 = {variable_two}".format(variable_one=var1, variable_two=var2))
The format() method will look for any opened and closed curly braces ‘{}’ and replace it with the specific value based on the order if no number or label has been set in between the curly braces.
replace:
As you know the str object is immutable that mean we can’t change or delete any character in the characters sequence using the indexing method, but the str object has method called replace() that takes three arguments:
- old: the character that we want to replace.
- new: the character that we want to be replacing the old one.
- count: this is an optional argument, it is the number of characters that we want to be replaced.
This method will create a new modified str boject and return it, it won’t change the original str object.
0var = "Apple"
1
2#OUTPUT: Akkle
3print(var.replace('p', 'k'))
4
5#OUTPUT: Akple
6print(var.replace('p', 'k', 1))
In the first call we have set the character ‘p’ to be replaced by the character ‘k’ and ignored the third argument (count) and the result was that all the ‘p’ characters has been replaced by ‘k’.
In the second call we have set the number ‘1’ as third argument in the replace method which means that we want only one ‘p’ character to be replaced.
lower and upper:
Python str object has a method called lower() that convert all uppercase characters to lowercase, and a method called upper() that convert all lowercase characters to uppercase:
0var = "HeLLo WoRld"
1
2#OUTPUT: hello world
3print(var.lower())
isalpha:
This method is used to check if the str object is a sequence of only alphabetical characters, it will return True if only alphabetical characters are in the sequence and False if not.
0var = "MyUsername"
1var2 = "Hello World"
2
3#OUTPUT: True
4print(var.isalpha())
5
6#OUTPUT: False
7print(var.isalpha())
isdigit:
This method is similar to our previous method, but this time this method will check if the str objects is a sequence of digits.
0var1 = "variable1"
1phone_number = "4452133684"
2#OUTPUT: Fale
3print(var.isdigit(var1))
4
5#OUTPUT: True
6print(var.isdigit(phone_number))
isalnum:
This method is the combination of the two previous methods ‘isalpha’ and ‘isdigit’, this will return True if the str object contain only alphabetical characters or only digits or both at the same time.
0#OUTPUT: True
1print("Hello".isalnum())
2
3#OUTPUT: True
4print("2455".isalnum())
5
6#OUTPUT: True
7print("Hello4452".isalnum())
You can read more about str methods that can be very useful for you: Python Docs.