Python | Reverse a String

In Python we can use various methods to reverse a string. Simplest way to reverse a string is to use the slice operation.

 str = "QnAPlus"
 print ("Original string: " + str)
 print ("Reversed string: " + str[::-1])

Output:

 $ python test.py
 Original string: QnAPlus
 Reversed string: sulPAnQ

General syntax of slice operation is string[start:end:step]. In our program start and end are not specified. That means the whole string will be considered. As the step is -1, the string will be returned in reverse order.

This is the simplest and recommended way to reverse a string in Python. In the following sections, we’ll discuss other methods for demonstration purposes.

Reverse a String Using Loop

 str = "QnAPlus"
 print ("Original string: " + str)
 rev_str = ""
 for c in str:
     rev_str = c + rev_str
 print ("Reversed string: " + rev_str)

The logic is simple. Here we started with an empty string, rev_str. Then for every character in the original string, str, we appended the character at the front of the rev_str.

Using Recursion

We can implement the same above logic using a recursive function.

 def reverse(str):
     if len(str) == 0: return ""
     return reverse(str[1:]) + str[0]
 str = "QnAPlus"
 print ("Original string: " + str)
 str = reverse(str)
 print ("Reversed string: " + str)

Using Python reversed() Method

 str = "QnAPlus"
 print ("Original string: " + str)
 print ("Reversed string: " + "".join(reversed(str)))

The reversed() function takes a sequence like list, tuple, string, range etc, as input and returns an iterator object containing the input sequence in reversed order. We can get the reverse string simply by joining the sequence contained by the returned iterator.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0