3 Common ways to Reverse a String in Python

One of the very common problems in any programming language is how to reverse a String.

Let’s see a few ways to do this in python.

1. Using String Slicing

well first of all the most easy way.. Here we are using the power of String Slicing. Just a single line command!

-1 at the last index means reading from end. and the first two empty index means that we are considering the whole string. 

mystring = "Hello World"
rev = mystring[::-1]print(rev)

 2. Using join method and reversed method

reversed function returns a reverse iterator over the values of sequence and join basically joins those with the given separator, which is ” (an empty string) in this case.

mystring = "Hello World"

rev = ''.join(reversed(mystring))

print(rev)

 

3. Using String concatenation and for loop

mystring = "Hello World"

rev = ""

for i in mystring):
rev = i + rev

print(rev)

Leave a Reply

Your email address will not be published.