codescracker
python

Python Program to Reverse a String



« Previous Program Next Program »

Reverse a String in Python

To reverse a string entered by the user in python, you have to ask from user to enter the desired string which is going to reverse to reverse that string and print the reversed string as output as shown in the program given below.

Python Programming Code to Reverse a String

Following python program ask from the user to enter a string to reverse that string and print it as output:

Here is the sample run of the above python program to illustrate how to reverse a string in python:

Reverse a String

# ----codescracker.com----

print("Enter the String:")
text = str(input())
revText = text[::-1]
text = revText
print("Reverse of Given String is:")
print(text)

Here is its sample run:

reverse string program python

Now supply the input say codescracker as string and press ENTER key to reverse it and print its reverse as shown in the snapshot given below:

reverse string python

Modified Version of Previous Program

# ----codescracker.com----

print(end="Enter the String: ")
text = str(input())
text = text[::-1]
print("\nIt's Reverse = " + text)

Here is its sample run with user input, Welcome to CodesCracker:

python reverse a string

Reverse a String using for Loop

# ----codescracker.com----

print(end="Enter the String: ")
text = str(input())
textTemp = ""
for i in text:
    textTemp = i + textTemp
text = textTemp
print("\nIt's Reverse = " + text)

Here is its sample run with user input, Welcome to Python:

reverse a string python

Reverse a String using Function

# ----codescracker.com----

def revstr(t):
    textTemp = ""
    for i in t:
        textTemp = i + textTemp
    return textTemp

print(end="Enter the String: ")
text = str(input())
text = revstr(text)
print("\nIt's Reverse = " + text)

Reverse a String using Recursion

# ----codescracker.com----

def revstr(t):
    if len(t)==0:
        return t
    else:
        return revstr(t[1:]) + t[0]

print(end="Enter the String: ")
text = str(input())
text = revstr(text)
print("\nIt's Reverse = " + text)

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker