Python string slice knowledge consolidation

  The slice operation (slice) can get a substring (part of a string) from a string. We use a pair of square brackets, a start offset start, an end offset end, and an optional step size step to define a slice.

Format: [start:end:step]

• [:] extracts the entire string from start (default position 0) to end (default position -1)
• [start:] extracts from start to end
• [:end] extracts from start to end - 1
• [start: end] Extract from start to end - 1
• [start:end:step] Extract from start to end - 1, one every step character
• The position/offset of the first character on the left is 0, the last character on the right A character has a position/offset of -1

examples:

'0123456'[12]  ------- '1'
'0123456'[152]  ------- '13'
'0123456'[:: - 1]  -------'6543210'
'0123456'[42:-1] ------- '43'

A few special examples are as follows:

 

Extract the last N characters:

>>> letter = 'abcdefghijklmnopqrstuvwxyz'
>>> letter[-3:]
'xyz'

 

From the beginning to the end, the step is N:

>>> letter[::5]
'afkpuz'

 

Reverse a string by setting the step size to a negative number:

>>> letter[::-1]
'zyxwvutsrqponmlkjihgfedcba'

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324814483&siteId=291194637