In python there is no direct function to reverse a string, to reverse a string we need to use slicing.
A slice extracts elements based on a start.
An extended slice extracts elements based on start and stop with step/stride.
Some examples of slicing:
>>> values="abcdefg" >>> values[1:3] 'bc' >>> values[2:-1] 'cdef' >>> values[:2] 'ab' >>> values[2:] 'cdefg' >>> values[::2] 'aceg' >>> values[::-1] 'gfedcba'
Slicing can be used for strings, lists, tuples, arrays and custom data structures as well.
If you observer above example the last slice values[::-1] is printing reverse string where we are using extended slicing.
>>> values[::-1] 'gfedcba' >>> 'xyz'[::-1] 'xyz'
Syntax of extended slice:
In our example by leaving begin and end off and specifying a step of -1 will reverses a string.