Strings are ordered sequences of character data. Indexing allows you to access individual characters in a string directly by using a numeric value. String indexing is zero-based: the first character in the string has index 0, the next is 1, and so on. In this lesson, you’ll learn string indexing syntax and practice with several examples:
>>> s = 'mybacon'
>>> s[0]
'm'
>>> s[1]
'y'
>>> s[6]
'n'
>>> s[len(s) - 1]
'n'
>>> s[7]
Traceback (most recent call last):
File "<input>", line 1, in <module>
s[7]
IndexError: string index out of range
Here’s some negative string indexing:
>>> s
'mybacon'
>>> s[-1]
'n'
>>> s[-4]
'a'
>>> s[-len(s)]
'm'
>>> s[-7]
'm'
>>> s[-8]
Traceback (most recent call last):
File "<input>", line 1, in <module>
s[-8]
IndexError: string index out of range
>>> t = ''
>>> type(t)
<class 'str'>
>>> t[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
t[0]
IndexError: string index out of range
>>> len(t)
0