Today we’ll be talking about using the string index in Python.
Here’s the video version:
As you know, strings are sequences, just like lists or tuples among other things, so they consist of smaller elements. With strings, the elements are single characters. They are arranged in a sequence, so in a specific order, with each character having its own address, or index what it’s called in the programming world. If you want to retrieve a specific character from a string, all you have to know is where to find it inside the string. If you know the index of the character you are looking for, you’re good to go.
By the way, indexing is typical of all sequences, not just strings. You can use it to get at a specific element of a list or tuple too. The difference is that in case of the other sequences, the particular elements may be virtually anything: strings, numbers, boolean values, or even other sequences. For now, though, let’s stick to strings, which are the subject of this article.
Forward and Backward Indexing
Strings can be indexed in both directions:
You use 0-based indices in the forward direction and -1-based indices in the backward direction.
You can print a particular character from the string by using its index in square brackets:
>>> text = "This is a text."
>>> print(text[0]) # print the first (at index 0) character
T
>>> print(text[14]) # print the 15th character, which is a period.
.
Negative Indices
Sometimes it’s more comfortable to use negative indices, especially if you need to retrieve the last element of a string. Normally you’d have to do something like this:
>>> text[len(text)-1] # so text[15-1] or text[14]
'.'
But it’s easier to do it this way:
>>> text[-1]
'.'
You can use other negative indices to count from the end:
>>> text[-2]
't'
>>> text[-11]
' '
>>> text[-3]
'x'
What Can Be Used as a String Index?
The index within the brackets may be calculated in any way. It may be an arithmetic expression, like for example:
>>> text[2 + 3] # = 5
'i'
or even quite a complex one like here:
>>> text[(-len(text) + 6 - 2 * 4) * (-1) - 7] # = 10
't'
If you try to use an index which is out of range, you’ll get an index error:
>>> text[50]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
The index must be an integer. If you try any other type, you’ll get a type error:
>>> text[5.42]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers