Sequence types such as lists, tuples, and strings in Python all support slicing.
1 The last element design
Slicing operations do not include the last element in the range because Python, like the Java language, starts with 0 as a subscript. The benefits of this are:
- When we see
[:x]
Syntax, you know that the slice contains X elements. - When we see
[start:stop]
Syntax, you know that the slice contains a stop-start element. - A sequence can be divided into two non-overlapping parts by a single subscript, such as
my_list[:x]
(Range: 0 to x-1) andmy_list[x:]
(The value ranges from x to len-1.)
l=[10, 20, 30, 40, 50, 60]
logging.info('l[:2] -> %s',l[:2])
logging.info('l[2:] -> %s',l[2:])
logging.info('l[:3] -> %s',l[:3])
logging.info('l[3:] -> %s',l[3:])
logging.info('l[1:2] -> %s',l[1:2])
Copy the code
Running results:
INFO - l[:2] -> [10, 20]
INFO - l[2:] -> [30, 40, 50, 60]
INFO - l[:3] -> [10, 20, 30]
INFO - l[3:] -> [40, 50, 60]
INFO - l[1:2] -> [20]
Copy the code
2. Slice at intervals
We can also use the syntax of S [a: b: c] to slice the elements between a and B in S with c intervals. If the value of c is negative, the value is reversed.
s='python'
logging.info('s[::3] -> %s',s[::3])
logging.info('s[::-1] -> %s',s[::-1])
logging.info('s[::-2] -> %s',s[::-2])
Copy the code
Running results:
INFO - s[::3] -> ph
INFO - s[::-1] -> nohtyp
INFO - s[::-2] -> nhy
Copy the code
3 Operation section
You can modify the sequence directly by placing the slice to the left of the assignment statement. If we use it as the object of the DEL operation, we can cut the sequence.
Luciano Ramalho gives this example:
L = list (range (10)) logging. The info (' l - > % s', l) l. [but] = [20, 30] logging info (' l - > % s', l) del l [for] logging. The info (' l - > % s', l) l [3: : 2] = [11, 22] logging. The info (' l - > % s', l) l [but] = [100] logging. The info (' l - > % s', l) l [but] = 100Copy the code
Running results:
INFO - l -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
INFO - l -> [0, 1, 20, 30, 5, 6, 7, 8, 9]
INFO - l -> [0, 1, 20, 30, 5, 8, 9]
INFO - l -> [0, 1, 20, 11, 5, 22, 9]
INFO - l -> [0, 1, 100, 22, 9]
Traceback (most recent call last):
...
l[2:5]=100
TypeError: can only assign an iterable
Copy the code
If the assigned object is a slice, it must be an iterable. Even if there is only one value, it must be converted to an iterable sequence. For example, if the last example assigns 100 directly to L [2:5], Python will raise TypeError: Can only assign an iterable.