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]
'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:

[begin:end:step]

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s