all Python 3Strings (str)term
String indexing
indexing/slicing
Access to a character of a string by index. Positive indices count from the start (0), negative ones from the end (-1).
Syntax
s[i] # i — целое число
An out-of-range index raises IndexError, while a slice quietly returns whatever fits: on an empty string s[0] blows up but s[0:1] just gives an empty string. Python has no separate character type — s[i] is a one-character string, and you cannot assign to it, since strings are immutable and the attempt raises TypeError. Indices count Unicode characters, not bytes.
Examples
s = 'Python'
print(s[0])
# → 'P'
print(s[1])
# → 'y'
print(s[-1])
# → 'n'
print(s[-2])
# → 'o'
print(s[5])
# → 'n'
s2 = 'AB'
print(s2[0], s2[1], s2[-1])
# → A B B
See also
Open in the full glossarydocs.python.orgReport an inaccuracy