Summarize to get a good understanding of python slices
>>> test = 'abcde'
>>>test[0]
'a'
>>> test[4]
'e'
>>> test[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> test[-1]
'e'
>>> test[-5]
'a'
>>> test[-6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Specify from [0] to [character string length-1] like this You can specify from the end by specifying with a minus
Use [(start offset): (end offset): (step)] to use
>>>test = '0123456789'
>>> #Extract all
...test[:]
'0123456789'
>>> #From 5 to the end
...test[5:]
'56789'
>>>#From 3 to 7
...test[3:7]
'3456'
>>>#Take out 5 from the end
...test[-5:]
'56789'
>>>#Extract every two from the beginning to the end
...test[::2]
'02468'
>>>#Display in reverse order
...test[::-1]
'9876543210'
>>>#From the 100th character to the end
...test[100:]
''
>>>#From the last 100 characters to the end
...test[-100:]
'0123456789'
Slice works fine even with missed offsets Reverse order display is very convenient
Recommended Posts