Line slices
In Python, you can select part of a string (
substring). To do this, use the operation of obtaining a slice (from the English
slicing)
The general view of the slicing operation is as follows
s[start:stop:step]
This command takes a slice from the string
s
starting from the character at index
start
up to the character at index
stop
(not including it) with step
step
(if not specified, step is 1)
Any part in brackets may be missing.
For example,
s1 = s[3:8]
means that characters from 3 to 7 are copied into string s1 from string s with step 1.
You can take negative indices, then the count is from the end of the string.
s = "0123456789"
s1 = s[-7:-2] # s1="34567"
If
start
is not specified, it is considered to be equal to zero (that is, we take it from the beginning of the string). If stop is not specified, then the slice is taken until the end of the string.
s = "0123456789"
s1 = s[:4] # s1="0123"
s2 = s[-4:] # s2="6789"
This is how easy it is to reverse a string:
s = "0123456789"
s1 = s[::-1] # s1="9876543210"
All characters of the string are iterated in increments of -1, which means that the characters will be iterated from the end. The entire row is involved because the start and end indexes are not specified.