Use [] to extract characters (strings) in python

The essence of a string is a sequence of characters. We can extract a single character at the changed position by adding [] after the string and specifying the offset in the []

Forward search:
the first character on the left, the offset is 0, the second offset is 1, and so on, until len(str) -1 is known

Reverse search:
the first character on the far right has an offset of -1, the penultimate offset is -2, and so on, until -len(str) is known

>>> a="abcdefghijklmnopqrstuvwxyz"
>>> a
'abcedfghijklmnopqrstuvwxyz'
>>> a[0]
'a'
>>> a[3]
'e'
>>> a[26-1]
'z'
>>> a[-1]
'z'
>>> a[-26]
'a'
>>> a[27]
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a[27]
IndexError: string index out of range

Guess you like

Origin blog.csdn.net/yue008/article/details/108594061