slice
Slice expression syntax is: [start_index : end_index : step]
where:
start_index
It represents the starting indexend_index
It indicates the end of the indexstep
Represents a step size, the step size is not 0, and the default value is 1
The slicing operation is in accordance with the step size, index taken from the start to the end of the index, but the index does not include the end (i.e. the end of the index minus 1) all elements.
python3
Support slicing data typeslist
,tuple
,string
,unicode
,range
- The results returned by the slice type consistent with the original object type
- Slice does not change the original object, but to re-generate a new object
The following is a list of columns:
Tuglie a
A simple example:
alist = [ 'A', 'B', 'C', 'D', 'E', 'F.'] ①alist [0:. 4:. 1]
②alist [0:. 4] Results: [ 'A', 'B ',' C ',' D '] ① and ② as a result, since the step size has a default value. 1 alist [0:. 4: 2] results: [' A ',' C ']
Omitted start_index
, retained end_index
, it will start from the first element, to cut end_index - 1
up element
alist[:4]
['A', 'B', 'C', 'D']
Retained start_index
, but will be omitted end_index
, it will start from the start index, cut to the last element:
alist[2:]
['C', 'D', 'E', 'F']
Omitted start_index
, end_index
and step
so it means it means slicing the entire sequence, which is a copy of a new sequence:
alist[:]
['A', 'B', 'C', 'D', 'E', 'F']
Is omitted start_index
, end_index
but retained step
, represents the entire sequence, the step value in accordance with rules divisible:
alist[::2]
['A', 'C', 'E']
At this point, if we step is set -1
, then you can easily get a reverse order of the sequence :
alist[::-1]
['F', 'E', 'D', 'C', 'B', 'A']
The following four expressions are equivalent:
FIG observation can be drawn on a column, consistent interval.
When sliced, make sure start_index
to end_index
direction and long walks step
in the same direction, otherwise it will cut out the empty sequence :
alist[0:4:-1]
[]
alist[3:0:2]
[]
Function with a microtome, a write function trim (str), similar in Python strip () function - end to end string is removed spaces: