Slicing operation (Slice) may acquire sub-string (part of a string) from a string. We use the square brackets, starting offset start, termination end offset step and optional steps to define a slice.
Format: [start: end: step]
- [:] Extracted from the beginning (default position 0) to the end (the default position -1) of the entire string
- [Start:] extracted from the start to the end
- [: End] extracted from the beginning to end - 1
- [Start: end] extracted from the start to the end - 1
- [Start: end: step] extracted from the start to the end - 1, each step extracting a character
- The first character position of the left / offset 0, the right of the last character position / offset is -1
Example:
Results enter a string in reverse order returns,: such as: 'abcdef' Returns: 'fedcba'
1 # way: string reversed step is set to -1 2 DEF re_sort (): . 3 S = INPUT ( 'Enter string string: >>') . 4 return S [:: - 1] from # beginning to the end in steps of -1 . 5 # re_sort obj = () . 6 # Print (obj) . 7 . 8 # way: by reversing the list . 9 DEF re_sort2 (): 10 S = iNPUT ( 'enter string string: >> ') . 11 Li = [] 12 is for I in S: 13 is li.append (I) 14 li.reverse () inverted list # 15 return .' ' the Join (Li) is converted into a string list # 16 obj2 = re_sort2() 17 print(obj2)