How to reverse a string in Python
In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios and needs.
There are 5 different ways to reverse a string, which are as follows:
- Loops
- Recursive functions
- Stack data structure
- Slicing
- reversed ()
Let’s get on to them one by one.
- Using loops:
Program:
def reverse_string(string):
str = ""
for i in string:
str = i + str
return str
string = input("Enter a string: ")
print ("The original string is : ",end="")
print (string)
print ("The reversed string(using loops) is : ",end="")
print (reverse_string(string))
Output:
Enter a string: Hello
The original string is: Hello
The reversed string (using loops) is: olleH
Explanation:
In the program, we took the string input from the user to reverse it. We made a function reverse_string to write the logic. Inside the function, the string is taken as a parameter. We took another empty string str. Then, we used a loop iterating through our string and appended characters of the string to the new string. The first character is appended first then the second is appended then the third.
Table: When string to be reversed is Hello
Value of i | Reversed string |
H | H |
E | eH |
L | leH |
L | lleH |
O | olleH |
- Using recursive functions:
Program:
def reverse_string (string):
if len (string) == 0:
return string
else:
return reverse_string (string [1:]) + string [0]
string = input ("Enter a string: ")
print ("The original string is : ", end= "")
print (string)
print ("The reversed string (using recursion) is : ", end= "")
print (reverse_string (string))
Output:
Enter a string: Hello
The original string is: Hello
The reversed string (using recursion) is: olleH
Explanation:
In the program, we used a recursive function “reverse_string”. In the function, we checked the length of the string. If the length is equal to 0, that means, the string is reversed and so, we return the string to the call. If not, we slice the string to [1:] then pass it as the parameter to the function appending the first character. This continues till the whole string gets reversed.
Table:
If we take the string as: Hello
String | string[1:] + string[0] |
Hello | ello + H = elloH |
ello | llo + e = lloeH |
Llo | lo + l = loleH |
Lo | o + l = olleH |
- Using the stack data structure
Stack is a data structure with the principle: First in last out or last in first out, which means that the element that is inserted into the stack at the last will be the first element that can be retrieved out from the stack.
Program:
def createStack ():
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 (string):
n = len (string)
stack = createStack ()
for i in range(0, n, 1):
push (stack, string [i])
string = ""
for i in range(0, n, 1):
string + = pop (stack)
return string
s = "Tutorials"
print ("The original string is : ", end="")
print (s)
print ("The reversed string is : ", end="")
print (reverse (s))
Output:
The original string is: Tutorials
The reversed string is: slairotuT
Explanation:
In the program, we used six functions:
- createStack () : To create the stack data structure
- size (stack) : For the size of the stack
- isEmpty (stack) : To check if the stack is empty
- push (stack, item) : To insert the elements into the stack
- pop (stack) : To retrieve the elements from the stack
- reverse (string) : To direct the mechanism and finally return the reversed string.
First, we defined a function called createStack in which we created an empty list with the name stack and returned it. In the second function, size, the stack is taken as the parameter and the length of the stack is found and returned. In the third function, isEmpty, stack is taken as a parameter and checked if the stack is empty or not. If the stack is empty then “True” is returned.
In the next function, push(), two parameters are taken, stack and the item to be inserted into the stack. Using the append function of lists; we append the item into the list. The next function is pop(), in which, stack is taken as a parameter, and in the body, the stack is checked if it is empty and if it is not empty, we call the pop function. This way, we delete the elements from the stack.
In the reverse function, we took the string we need to reverse as the parameter. The length of the string is found and is stored in n. Now, using the createStack function, a stack (list) is created. Now we iterated through the elements of the string and push them into the empty list. Now, we initiated a new empty string to store the reversed string. Then, we concatenated the new string with the pop () function in each iteration. Now, the reversed string is stored in the new string and is returned.
Here, the important point to be understood is that, the pop function is a recursive function and once, we call it, one after the other the characters of the string are deleted and returned, and then are appended into the new string and so the string will be reversed.
The order of insertion into the stack:
T – U – T – O – R – I – A – L - S
S |
L |
A |
I |
R |
O |
T |
U |
T |
When popped out, the order will be:
S – L – A – I – R – O – T – U – T
- Slicing
Program:
def reverse_string (string):
string = string [ : : -1]
return string
s = "Tutorials"
print ("The original string is : ", end = "")
print (s)
print ("The reversed string is : ", end = "")
print (reverse_string (s))
Output:
The original string is : Tutorials
The reversed string is : slairotuT
Explanation:
It is a simple predefined syntax in Python called string slicing. When we specify a string [start : stop : step], the string will be sliced or broken down from the start index to the stop – 1 index with gaps of step. In the program, we gave the step as -1 and we did not specify the start and stop indexes, which mean the whole string is sliced but with a negative step of -1 which means the string will be sliced from backwards and so it will be reversed.
- reversed () function:
Program:
def reverse_string(string):
string = "".join(reversed(string))
return string
s = "Tutorials"
print ("The original string before reversing is : ",end="")
print (s)
print ("The reversed string is : ",end="")
print (reverse_string(s))
Output:
The original string before reversing is : Tutorials
The reversed string is : slairotuT
Explanation:
Reversed () is a predefined function in Python. It returns the reversed iterator of the specified string. These iterated characters are joined to the empty string to make it a string and so, the string will be reversed.
Above explained ways are the five different ways of reversing strings in Python programming language. These ways are used based on the situation and the feasibility in the block of code.