Python program to reverse a string with examples

In this python tutorial, you will learn about the python program to reverse a string also we will check:

  • Python program to reverse a string
  • Python program to reverse a string from user input
  • Python program to reverse a string using recursion
  • Python program to reverse a string using for loop
  • Python program to reverse a string using slicing
  • Python program to reverse a string word by word
  • Python program to reverse a string using function
  • Python program to reverse a string using while loop
  • Python program to reverse a string without using recursion
  • Python program to reverse a string without using function in python
  • Python program to reverse a string using stack
  • Python program to reverse a string except special characters
  • Python program to reverse each word in a string
  • Python code to reverse words in a string
  • Reverse each word in a sentence in python
  • Python program to reverse a string without using reverse function
  • Python program to reverse a string word by word using class

Python program to reverse a string

Let see python program to reverse a string.

  • Firstly, we have declared the reverse() function and passed the str as an argument.
  • Inside the function declare an empty string variable as a string that will hold the reversed string.
  • The for loop iterate every element of the given string and store in the string variable
  • return string will return the reverse string to the caller function
  • At last, it will return the reverse order and the result will be printed.

Example:

def reverse(str):
    string = " "
    for i in str:
        string = i + string
    return string
str = "PythonGuides"
print("The original string is:",str)
print("The reverse string is:", reverse(str)) 

To get the output, I have used print(“The reverse string is:”, reverse(str)). You can refer to the below screenshot for the output.

Python program to reverse a string
Python program to reverse a string

The above code we can use to reverse a string in Python.

You may like, How to print factorial of a number in Python.

Python program to reverse a string from user input

Here, we will see python program to reverse a string from user input.

  • Firstly the user will enter a string.
  • Empty string str = ‘ ‘ is created which will hold the reversed string.
  • The for loop iterate every element of the given string
  • At last, it will return the reversed string and the result will be printed.

Example:

my_str = input("Please enter your own String : ")
str = ''
for i in my_str:
    str = i + str
print("\nThe Original String is: ", my_str)
print("The Reversed String is: ", str)

To get the output, I have used print(“The Reverse String is: “, (str)). You can refer to the below screenshot for the output.

Python program to reverse a string from user input
Python program to reverse a string from user input

The above code, we can use to reverse a string from user input in Python.

Python program to reverse a string using recursion

Here, we will see python program to reverse a string using recursion.

  • We can also reverse a string using recursion. Python Recursion is the process where a function calls itself.
  • Firstly, we have declared the reverse() function and passed the str1 as an argument
  • if len(str1) == 1 is used to check the length of string which is the base condition of recursion. If the length of the string is 1, then the string is returned, and if not then call the function recursively.
  • The slice operator will slice the string expects the first character and concatenate it to the end of the slice string
  • At last, it will return the reverse order and the result will be printed.

Example:

def reverse(str1):
    if len(str1) == 1:
        return str1
    else:
        return reverse(str1[1:])+str1[0]
str1 = "PythonGuides.Com"
print("The given string is:", str1)
print("Reversed string is:", reverse(str1))

To get the output, I have used print(“Reverse string is:”, reverse(str1)). You can refer to the below screenshot for the output.

Python program to reverse a string using recursion
Python program to reverse a string using recursion

This is how to reverse a string using recursion in Python.

Python program to reverse a string using for loop

Now, we will see python program to reverse a string using for loop.

  • Firstly, we have declared the reverse() function and passed the str as an argument.
  • Inside the function declare an empty string variable as a string that will hold the reversed string.
  • The for loop iterate every element of the given string and store in the string variable
  • return string will return the reverse string to the caller function
  • At last, it will return the reverse order and the result will be printed.

Example:

def reverse(string):
    s = " "
    for i in string:
        s = i + s
    return s
string = "HappyLearning"
print("The original string is:",string)
print("The reverse string is:", reverse(string)) 

To get the output, I have used print(“The reverse string is:”, reverse(string)). You can refer to the below screenshot for the output.

Python program to reverse a string using for loop
Python program to reverse a string using for loop

The above python code, we can use to reverse a string using for loop in Python.

You may also like, Python For Loop with Examples.

Python program to reverse a string using slicing

Let’s see python program to reverse a string using slicing.

  • Firstly, we have declared the reverse() function and passed the string as an argument.
  • The slice offers to put a “step” field as [start, stop, step], and giving no filed as start and stop indicates the default to 0 and string length respectively.
  • Here, -1 denotes from the end and stops at the start and then we get the reverse string.
  • At last, it will return the reverse order and the result will be printed

Example:

def reverse(string): 
    string = string[::-1] 
    return string 
str= "Guides"
print ("The original string is : ",end="") 
print (str) 
print ("The reversed string is : ",end="") 
print (reverse(str)) 

To get the output, I have used print(reverse(str)). You can refer to the below screenshot for the output.

Python program to reverse a string using slicing
Python program to reverse a string using slicing

The above Python program to reverse a string using slicing.

Python program to reverse a string word by word

Now, we will see python program to reverse a string word by word.

  • Firstly, I have declared the string as “Python guides is best”
  • The string.split() is used to split the sentence into a list of words
  • An empty list reverse_str is used for reversing each word of the string in the list individually.
  • res = ” “.join(reverse_str) is used for joining the new list of words to form a new string.
  • At last, it will return the reverse string word by word and the result will be printed.

Example:

string = "Python guides is best"
word = string.split()
reverse_str = []
for i in word:
    reverse_str.append(i[::-1])
res = " ".join(reverse_str)
print("The reversed string word by word is:",res)

To get the output, I have used print(“The reversed string word by word is:”,res). You can refer to the below screenshot for the output.

Python program to reverse a string word by word
Python program to reverse a string word by word

The above code, we can use to reverse a string word by word in Python.

You may like, How to concatenate strings in python.

Python program to reverse a string using function

Here, we will see python program to reverse a string using function.

  • Firstly, we have defined the reverse() function and passed the str as an argument.
  • Inside the function declare an empty string variable as a string that will hold the reversed string.
  • The for loop iterate every element of the given string and store in the string variable
  • return string will return the reverse string to the caller function
  • At last, it will return the reverse order and the result will be printed by calling the function.

Example:

def reverse(str1):
    string = " "
    for i in str1:
        string = i + string
    return string
str1 = "LearningPython"
print("The original string is:",str1)
print("The reverse string is:", reverse(str1)) 

To get the output, I have used print(“The reversed string is:”, reverse(str1)). You can refer to the below screenshot for the output.

Python program to reverse a string using function
Python program to reverse a string using function

This is the Python program to reverse a string using function.

You may like, Python Anonymous Function (Lambda Function)

Python program to reverse a string using while loop

Now, we will see python program to reverse a string using while loop.

  • Firstly, I have declared the string variable as “HappyLearning”.
  • An empty string is created reverse_Str = “”
  • count = len(string) is used to find the length of the string and save it in the count variable.
  • We initialized a while loop with a value of the string
  • In each iteration, the value of string[count-1] concatenates to the reverse_Str and decrements the count value.
  • A while completed its iteration and returned the reverse order string.

Example:

string = "HappyLearning"
print ("The original string  is : ",string)   
reverse_Str = "" 
count = len(string)
while count > 0:   
    reverse_Str = reverse_Str + string[ count - 1 ]
    count = count - 1   
print ("The reversed string using a while loop is : ",reverse_Str)

To get the output, I have used print(“The reversed string using a while loop is : “,reverse_Str). You can refer to the below screenshot for the output.

Python program to reverse a string using while loop
Python program to reverse a string using while loop

This is how to reverse a string using while loop in Python.

Also read, Python While Loop Example.

Python program to reverse a string without using recursion

Let’s see python program to reverse a string without using recursion.

  • First, we will take a string from the user.
  • Then we will use string slicing to reverse the string.
  • At last, print the reversed string to get the output.

Example:

my_string = str(input("Enter a string: "))
print("Reverse of a string without using recursion is: ")
print(my_string[::-1])

To get the output, I have used print(my_string[::-1]). You can refer to the below screenshot for the output.

Python program to reverse a string without using recursion
Python program to reverse a string without using recursion

The above code, we can use to reverse a string without using recursion in Python.

Python program to reverse a string without using function in python

Here, we will see python program to reverse a string without using function in python.

  • Firstly, we take a string and store it in a variable my_string
  • We are not using any function so we will take an empty string “str” to concatenate it with each letter of a string using a loop.
  • for loop is used for iterating variable
  • Now, we will concatenate the empty string str with the value of an iterating variable which will reverse the string.

Example:

my_string=("Reverseofstring")
str1=""
for i in my_string:
    str1=i+str1
print("The Reversed string is:",str1)

To get the output, I have used print(“The Reversed string is:”,str1). You can refer to the below screenshot for the output.

Python program to reverse a string without using function in python
Python program to reverse a string without using function in python

The above code, we can use to reverse a string without using function in python.

Python program to reverse a string using stack

Now, we will see python program to reverse a string using stack.

  • Firstly, we will define a function as def revStack() and also we will create an empty stack.
  • After that, we will define another function to determine the size of the stack.
  • The stack will be empty if the size is 0
  • def push function is for adding an item to the stack and it increases size by 1.
  • the def pop function is used to remove an item from the stack and it decreases the size by 1
  • def reverse(str) is used for reversing a string.
  • Now, we will create an empty stack as stack = revStack()
  • We will now push all the characters of a string to stack
  • Making the string empty as all the character are saved in the stack
  • str+=pop(stack) is used to pop all characters of string and put them back to a string.
  • At last, print is used to get the reversed string.

Example:

def revStack(): 
    stack=[] 
    return stack 
def size(stack): 
    return len(stack) 
def isEmpty(stack): 
    if size(stack) == 0: 
        return true 
def push(stack,item): 
    stack.append(item) 
def pop(stack): 
    if isEmpty(stack): return
    return stack.pop() 
def reverse(str): 
    n = len(str) 
    stack = revStack() 
    for i in range(0,n,1): 
        push(stack,str[i]) 
    str="" 
    for i in range(0,n,1): 
        str+=pop(stack) 
    return str
str ="CodingisFun"
str = reverse(str) 
print("Reversed string is: " + str) 

To get the output, I have used print(“Reversed string is: ” + str). You can refer to the below screenshot for the output.

Python program to reverse a string using stack
Python program to reverse a string using stack

This is how to reverse a string using stack in Python.

Python program to reverse a string except special characters

Let’s see python program to reverse a string except special characters.

  • Firstly, we will define a function as def reverseStr(msg)
  • We will loop from the last index until half of the index
  • if msg[i].isalpha() is used to match the character whether it is an alphabet or not.
  • we have created temporary characters array called temp[]
  • copy the alphabetic characters from a given array to temp[]
  • Then we will reverse temp[] using string reverse
  • Now, we traverse input string and temp in a single loop
  • At last, print is used to reverse a string except special characters, and the special character is not moved anywhere.

Example:

def reverseStr(msg): 
    index = -1   
    for i in range(len(msg)-1, int(len(msg)/2), -1):      
        if msg[i].isalpha(): 
            temp = msg[i] 
            while True: 
                index = index + 1
                if msg[index].isalpha(): 
                    msg[i] = msg[index] 
                    msg[index] = temp 
                    break
    return msg 
my_string = "P,y!!t.h,o'n,guide"
print ("My string is: ", my_string) 
my_string = reverseStr(list(my_string)) 
print("The reversed string except special characters:","".join(my_string)) 

To get the output, I have used print(“The reversed string except special characters:”,””.join(my_string)). You can refer to the below screenshot for the output.

Python program to reverse a string except special characters
Python program to reverse a string except special characters

The above code, we can use to reverse a string except special characters in Python.

Python program to reverse each word in a string

Now, we will see python program to reverse each word in a string.

  • Firstly, we have defined the function as def reverseword(str).
  • Now, we will split the sentence into a list of words
  • Reversing each word and creating a new list of words by using the list comprehension
  • To form the new sentence join() is used for joining the words in the list.
  • print(reverseword(str)) is used for calling and the function to get a new string.

Example:

def reverseword(str): 
    word = str.split(" ")  
    newWord = [words[::-1] for words in word] 
    new = " ".join(newWord) 
    return new
str = "Python Guides is good for beginners"
print(reverseword(str))

To get the output, I have used print(reverseword(str)). You can refer to the below screenshot for the output.

Python program to reverse each word in a string
Python program to reverse each word in a string

This is how to reverse each word in a string in Python.

Python code to reverse words in a string

Let see python code to reverse words in a string.

  • Firstly, we have defined the function as def reverse(Sentence).
  • We will split the sentence into a list of words
  • then we will reverse the split string list and join using the space.
  • return rev_sentence is used for returning the joined string
  • At last, print reverse words in a string

Example:

def reverse(sentence):  
    words = sentence.split(' ')    
    rev_sentence = ' '.join(reversed(words))   
    return rev_sentence  
if __name__ == "__main__":  
    input = 'Python is Interesting'
    print (reverse(input))

To get the output, I have used print(reverse(input)). You can refer to the below screenshot for the output.

Python code to reverse words in a string
Python code to reverse words in a string

This is how to reverse words in a string in Python.

Reverse each word in a sentence in python

Here, we will see how to reverse each word in a sentence in python.

  • Firstly, we have defined the function as def revwordSentence(Sentence).
  • Now, we will split the sentence into a list of words
  • To form the new sentence join() is used for joining the words in the list.
  • At last, print the reversed word in the sentence

Example:

def revwordSentence(Sentence): 
    return ' '.join(word[::-1] 
    for word in Sentence.split(" ")) 
Sentence = "Learn with Understanding"
print(revwordSentence(Sentence))  

To get the output, I have used print(revwordSentence(Sentence)). You can refer to the below screenshot for the output.

Reverse each word in a sentence in python
Reverse each word in a sentence in python

This is the code, we can use to reverse each word in a sentence in python.

Python program to reverse a string without using reverse function

Now, we will see python program to reverse a string without using reverse function.

  • Firstly, we take a string and store it in a variable string
  • We are not using any function so we will take an empty string “str” to concatenate it with each letter of a string using a loop.
  • for loop is used for iterating each element.
  • Now, we will concatenate the empty string str with the value of an iterating variable which will reverse the string.

Example:

string=("PythonTest")
str=""
for i in string:
    str = i+str
print("The Reversed string is:",str)

To get the output, I have used print(“The Reversed string is:”,str). You can refer to the below screenshot for the output.

Python program to reverse a string without using reverse function
Python program to reverse a string without using reverse function

This is the Python program to reverse a string without using reverse function.

Python program to reverse a string word by word using class

Here, we will see python program to reverse a string word by word using class.

  • Firstly, I have created a class called Reverse
  • After that, we have defined the function inside the class
  • Now, we will split the sentence into a list of words, and to form the new sentence join() is used for joining the words in the list.
  • At last, print Reverse().reverse_word(‘Welcome to Python’) to get the output.

Example:

class Reverse:
    def reverse_word(self, str):
        return ' '.join(reversed(str.split()))
print(Reverse().reverse_word('Welcome to Python'))

To get the output, I have used print(Reverse().reverse_word(‘Welcome to Python’)). You can refer to the below screenshot for the output.

Python program to reverse a string word by word using class
Python program to reverse a string word by word using class

This is how to reverse a string word by word using class in Python.

You may like the following Python tutorials:

In this Python tutorial, we have learned about the Python program to reverse a string. Also, we covered these below topics:

  • Python program to reverse a string
  • Python program to reverse a string from user input
  • Python program to reverse a string using recursion
  • Python program to reverse a string using for loop
  • Python program to reverse a string using slicing
  • Python program to reverse a string word by word
  • Python program to reverse a string using function
  • Python program to reverse a string using while loop
  • Python program to reverse a string without using recursion
  • Python program to reverse a string without using function in python
  • Python program to reverse a string using stack
  • Python program to reverse a string except special characters
  • Python program to reverse each word in a string
  • Python code to reverse words in a string
  • Reverse each word in a sentence in python
  • Python program to reverse a string without using reverse function
  • Python program to reverse a string word by word using class