Python reverse a string with slicing


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]
>>> values[2:-1]
>>> values[:2]
>>> values[2:]
>>> values[::2]
>>> values[::-1]

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]
>>> 'xyz'[::-1]

Syntax of extended slice:


In our example by leaving begin and end off and specifying a step of -1 will reverses a string.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s