How to reverse the content of a string using slicing in Python

Let’s say you want to revers the content of a string in Python. For example instead of “Dan” you want to be displayed “naD” (in reverse).

You can do it by using slice notation. You select all of the individual characters but in reverse order.

>>> s1 = 'Dan'
>>> s2 = s1[::-1]
>>> s2
'naD'

The [::-1] means:

  • The first : (colon) is the index of the character where the whole process begins
  • The second : (colon) is the index of the last character where the whole process ends
  • The -1 means each character (one by one) starting from the end

Let’s choose a longer string and let’s replace -1 with 2. The result doesn’t need any explanations.

>>> s1 = 'Dumitrache'
>>> s2 = s1[::2]
>>> s2
'Dmtah'

Here you have another example:

>>> s1 = 'Dan Dumitrache is a web developer!'
>>> s2 = s1[::-1]
>>> s2
'!repoleved bew a si ehcartimuD naD'

Leave a Reply