The slice operator is a sequence name followed by a square bracket, with a pair of optional digits in the square brackets, separated by a colon. Note that this is very similar to the index operator you are using. Remember that the number is optional, and the colon is required.
The first number in the slice operator (preceded by a colon) indicates where the slice begins, and the second number (after the colon) indicates where the slice ends, and the third number (after the colon) represents the number of tile intervals . If you do not specify the first number, Python starts from the beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence. Note that the returned sequence starts at the start position and ends just before the end position. That is, the start position is contained in the sequence slice, and the end position is excluded from the slice.
This shoplist[1:3]
returns a slice that contains two items, starting at position 1, including position 2, but stopping a sequence slice at position 3. Similarly, shoplist[:]
a copy of the entire sequence is returned. Shoplist[::3] Return position 3, position 6, Position 9 ... The sequence slice.
You can make slices with negative numbers. negative numbers are used at the beginning of the end of the sequence . For example, a shoplist[:-1]
sequence slice that contains all items except the last item is returned, and shoplist[::-1] returns the reverse sequence slice. Use the Python interpreter to interactively try out different slices of the specified combination, i.e. you can see the results immediately at the prompt. The magic of sequences is that you can access tuples, lists, and strings in the same way. :
Example:
>>> str1 = ' i2sl54ovvvb4e3bferi32s56h; $c 43.sfc67o0cm99 '
>>> Str1[::3]
' Ilovefishc.com '
Slicing operations for Python