Today we’ll be talking about slicing strings. This is what you do if you need to make a substring from a string.
Slicing Strings Basics
You can slice strings. If you need just part of a string, or a slice, you can specify the start index and the past index in square brackets. The square brackets are sometimes referred to as the slice operator in this context. The start index is included, the past index is not included.
So, given the string:
>>> text = "unbelievable"
If you need the first four characters, the start index should be 0 and the past index should be 4. This way you will get a slice containing the characters at indices 0, 1, 2, and 3.
>>> text[0:4]
'unbe'
If you need just one character, you can just use its index. You can also use slicing. So, if you need the character at index 4 in the string above, you can specify the range to be from index 4 to 5, the latter not being included:
>>> text[4:5]
'l'
Skipping Indices
If you need a slice from the beginning of a string, the start index should be 0. But this is the default value, which means you can skip it. This is how you can get the characters from index 0 to 7:
>>> text[:8]
'unbeliev'
This works exactly the same as if you used the start index explicitly:
>>> text[0:8]
'unbeliev'
Similarly, if you skip the past index, you will get a slice from the start index to the end of the string:
>>> text[3:]
'elievable'
You can also use negative indices. This is how you can get the slice from the beginning to index -6 (-5 is not included):
>>> text[:-5]
'unbelie'
If you omit both the start index and the past index, the slice will contain all the characters of the original string. This is how you can easily copy a string.
>>> text[:]
'unbelievable'
Step
You can also specify the step. Just add one more argument in the brackets. So, if you want a slice with every other character between index 2 and 9, this is how you do it:
>>> text[2:10:2]
'blea'
And here’s how you can get every third character from the whole string:
>>> text[::3]
'ueeb'
If the step is negative, the elements are in reversed order. Here you have every other character:
>>> text[8:1:-2]
'aelb'
And here are all the elements, but in reversed order:
>>> text[::-1]
'elbaveilebnu'
Here’s the video version: