How to reverse a string in Python?

In python, the string data types are immutable which means the value of the string cannot be changed or updated. Hence, the built-in function reverse() is not supported by string data-type in python. The other method to reverse the string in python is as follows.

Reversing a string using for loop

In the below code, we use a variable my_str to take user input and another variable rev is declared as an empty string. A for loop is used to iterate over the my_str and add each character to the beginning of the string variable rev.

my_str = input("Enter a string:")
rev = ""
for i in my_str:
    rev = i + rev
print(rev)

OUTPUT

Enter a string: HELLO WORLD!!
!!DLROW OLLEH 

Reverse a string using list :

We use the variable my_str to take user input. The list constructor is used for building a list from the string. The list supports the reverse() function hence is used to reverse the list. At the final step, the join method takes all the items in an iterable and concatenates them in one string.

my_str=input("Enter the string:")  
my_list=list(my_str)
my_list.reverse()
print("".join(my_list))

OUTPUT

Enter the string:Hello World!!!
!!!dlroW olleH

Reverse a String using pop() in the list

In the below code, we use the variable my_str to take user input and declare a variable my_list. We iterate over each character of my_str and push it into the my_list. An empty string variable rev is initialized.

A while loop is used to iterate over the elements of the my_list until the stack becomes empty. The pop operation is used to remove the element one by one from the end and concatenate it to the reverse string variable.

my_str = input("Enter the string:")
my_list = []
for i in my_str:
    my_list.append(i)
rev = ""
while my_list:
    element = my_list.pop()
    rev += element
print(rev)

Output

Enter the string: Hello World
dlroW olleH

Reverse a string using the extended slice

The syntax for an extended slice is [start: stop: step]. The value for the start and stop field is optional and if the value is not provided it sets the default value for start to '0' and stop to string length. Step -1 indicates starting from the end and stop at the start hence, reversing the string.

my_str=input("Enter the string:")
rev=my_str[::-1]
print(rev)​

OUTPUT

Enter the string: Hello World
dlroW olleH   
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions