How To Reverse A String In Python

Author: Neeraj Avinash

Many programming languages have built-in reverse() function to reverse a string. Unfortunately there is no built-in reverse function available in standard python.

In this article we will see one of many ways to reverse a string.

For reversing a string we will complete the program in these steps:

  • Ask user to provide a string
  • Loop through the user input to reverse a string
  • At last we will display original string and reversed string

Implementation

Create a file with the name reverse.py and write the code below 

''' Program is supposed to reverse a string '''

userInput = input("Please provide string to reverse\n")

# revStr is the reversal string
revStr = ""

for i in userInput:
    revStr = i + revStr

print("Original String ", userInput)
print("Reversed String ", revStr)

 

Lets understand the program

 

1. Take User input

First we ask user to provide the string that we need to reverse. For taking user input from console we are using input function that is part of standard Python.

userInput = input("Please provide string to reverse\n")

2. Loop through the user input and reverse the string

We are using for loop to iterate through the user input. We have created a variable outside the for loop that will hold the reversed string

revStr = ""

for i in userInput:
   revStr = i + revStr

Here the logic is that we append the value of the revStr variable into current character in the string and assign the updated value to revStr variable.

3. Print Reversed String

Finally we are printing the original string and reversed string

print("Original String ", userInput)
print("Reversed String ", revStr)

 

In the terminal type in the command python3 reverse.py and provide the string and hit enter.

Output

If you provide the input value India you would get the output

Original String  India
Reversed String  aidnI

 

Last Updated - Sept. 19, 2024
  • Become Instructor

    Start helping millions of people

    Join Now
  • Start Learning

    Start Learning with ease

    Join Now

Connect With Us