Slice of python weapon

 slice

Slice expression syntax is: [start_index : end_index : step]where:

  • start_indexIt represents the starting index
  • end_indexIt indicates the end of the index
  • stepRepresents 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.

  • python3Support slicing data types list, 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 - 1up 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_indexand stepso 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_indexbut 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:

alist[0:4]
['A', 'B', 'C', 'D']
alist[0:-2]
['A', 'B', 'C', 'D']
alist[-6:4]
['A', 'B', 'C', 'D']
alist[-6:-2]
['A', 'B', 'C', 'D']

FIG observation can be drawn on a column, consistent interval.

When sliced, make sure start_indexto end_indexdirection and long walks stepin 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:

>>> def trim(str):
...     while str[:1]==' ':
...             str = str[1:]
...     while str[-1:] == ' ':
...             str = str[:-2]
...     return str
...
>>> trim('  abc  hh  welcome!      ')
'abc  hh  welcome!'

Guess you like

Origin www.cnblogs.com/ltb6w/p/11145034.html