string slices for Python:
You can either forward or reverse slice, and can even slice, odd slice (both support forward reverse)
First, the index, the Python string (the array is also the same), the index default starting from 0, if the reverse slice, then the last string (the last element of the array) is the index of-1.
When the index is negative, the count starts from the right side of the string.
The basic mode of slicing is:
Str[start:end:step]
Any of them can be empty.
The end value of the index, cannot be taken, the last value to be taken is an index-1 corresponding element (in fact, because it is the index subscript starting from 0 to count the reason)
1. If the starting index is omitted, if the ending index is a number greater than 0, the starting index is 0
ie str[:n] = str[0:n]
>>> str = ' ABCDEFG ' >>> str[:1] ' a ' >>> str[0:1] ' a '
>>> Str[:3] ' abc ' >>> STR[0:3] ' abc '
2. If the end index is omitted, if the starting index is greater than 0. Indicates that the end index is the last, and this condition is different from the end index equals
>>> str[2:] ' CDEFG ' >>> str[2:7] ' CDEFG '
3. If you omit step and omit end, step defaults to 1, that is, forward slicing, omit end, and start is positive, as previously said, indicates end is the last character.
>>> str[2:] ' CDEFG ' >>> str[2::1] ' CDEFG '
3.1 If step is negative, indicates a reverse slice, or is called reversed slice
>>> str = ' ABCDEFG ' >>> str[2::-1] ' CBA '
3.1.1 In reverse section, if End or start which omitted, the previous article has been expressed.
3.1.2 If you want to do odd slices, make a fuss about the step selection:
>>> str = ' ABCDEFG ' >>> str[::2] ' Aceg '
4. Now indicate the case where start or end is negative:
4.1
This needs to be combined with step to say that if step is positive (omitting step, the default is positive, which is 1).
In this case, start at the corresponding position starting at start, backward, take the character, until the end of the string.
>>> str = ' ABCDEFG ' >>> str[-3::] ' EFG ' >>> str[-6::] ' BCDEFG ' >>> str[-6:] ' BCDEFG '
4.2 If step is negative, when start is negative,
Step 1 indicates a reverse slice, which is reversed. And start is a negative number, starting with the element corresponding to the negative index.
#-6 corresponds to B, 1 for reverse slicing >>> str = ' ABCDEFG ' >>> str[-6::-1] ' ba '
This article is from the Linux and networking blogs, so be sure to keep this source http://khaozi.blog.51cto.com/952782/1852078
Python string slices