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'[1:2] ------- '1'
'0123456'[1:5:2] ------- '13'
'0123456'[:: - 1] -------'6543210'
'0123456'[4:2:-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'