Reverse multiple strings in Python

A String in Python is an ordered list of characters. Several important operations can be performed on strings, and one of them is reversing a string. Reversing a string may not have direct use-cases, however, there are several indirect use cases such as finding if a string is a palindrome or not, and so on. 

Programming languages such as Java, C++, and JavaScript have direct functions called reverse() which are invoked on strings, to reverse them quickly and efficiently. Unfortunately, Python doesn’t have an in-built function to reverse strings. 

However, there are several other workarounds that you can use to reverse a string in Python. In this comprehensive guide, you will look through different techniques that are done to do the same. These techniques would require knowledge of other Python concepts such as slicing, functions, recursion, loops, stacks, and so on. 

So, with no further ado, let’s discuss all of them one-by-one.

Python Training Course

Learn Data Operations in PythonExplore Course

Reverse multiple strings in Python

Using a Simple For-loop

Loops in Python allow you to iterate through iterables like lists, strings, dictionaries, etc., and perform any kind of operation on each of the elements. You can use a for loop in Python to reverse a string. Look at the code below for better clarity.

def reverseString(s):

   reversedString = ""

   for char in s:

       reversedString = char + reversedString

   return reversedString

s = "Simplilearn"

print("The original string was - ", s)

print("The reversed string is - ", reverseString(s))

In the above program, you looked at creating a simple function that takes an input as a string. And then returned the reversed string as the output. Inside the function, you saw the use of a simple for loop, intelligently. First, you created a variable and initialized it to an empty string. Then, you saw the use of a for loop to iterate through the characters of the input string one-by-one and joined each of the characters to the beginning of the string. Let’s understand it step-by-step.

Initially, the variable ‘reversedString’ is empty.

Current reversedString

Current Character

New reversedString = Current Character + Current reversedString

“”

S

S

S

i

iS

iS

m

miS

miS

p

pmiS

pmiS

l

lpmiS

lpmiS

i

ilpmiS

ilpmiS

l

lilpmiS

lilpmiS

e

elilpmiS

elilpmiS

a

aelilpmiS

aelilpmiS

r

raelilpmiS

raelilpmiS

n

nraelilpmiS

Let’s verify the output by executing the code.

Reverse multiple strings in Python

You can see that we have the right output.

Reverse a String in Python using Recursion

Recursion is an important programming concept you need to master. There are several uses of recursion and you can even use it to reverse a string in Python. Let’s see how to do so.

def reverseString(inputString):

   if len(inputString) == 0:

       return inputString

   else:

       return reverseString(inputString[1:]) + inputString[0]

inputString = "Simplilearn"

print ("String before reversing is: ", inputString)

print ("String after reversing is: ", reverseString(inputString))

Above, the program has created a function that takes the initial input as the input string. For that, it has created the base condition that - if the current string has a length 0, then you can return the current string because it will already be completely reversed by then. And for the else part, you have recursively called the same function on the remaining part of the string except for the first character and then concatenate it with the first character. Let’s verify the output.

Reverse multiple strings in Python
 

You can see that we have successfully reversed the string using recursion.

Reverse a String in Python using a Stack

A stack is a data structure that allows pop and push operations on it. Consider it as a stack of books. You can take out or pop a book only from the top and even push back or keep a book only on the top of the stack of books. Hence, it’s considered to be LIFO (Last In First Out). You can use a stack to reverse a string in Python. In fact, recursion also internally uses a stack. Consider the program below for better understanding.

def push(stack,item):

   stack.append(item)

def pop(stack):

   if(len(stack)==0):

       return

   return stack.pop()

def reverseString(string):

   stack = []

   for char in string:

       push(stack, char)

   string = ""

   while(len(stack)!=0):

       string = string + pop(stack)

   return string

string = "Simplilearn"

print("String before reversal is: ", string)

print("String after reversal is: ", reverseString(string))

In the above program, you have implemented the standard push and pop operations of a stack. You have then created another function called the reverseString. In this function, you took the input string as a parameter, initialized an empty stack, and pushed all the characters of the string one-by-one inside the stack. Next, you saw how to make the string empty. Then, you ran a while loop and popped each element of the stack until it became empty and appended the popped character back to the string. Finally, you returned the resultant string, which is the reversed string of the original one.

Let’s verify the output by running the program.

Reverse multiple strings in Python

Use reversed() Method to Reverse a String in Python

You can also use the reversed method in Python which returns a reversed object or iterator of the input string. The only thing you need to do is to perform an additional join operation on the resultant reversed object and return the new string. Let’s check out the below program.

def reverseString(inputString):

   inputString = "".join(reversed(inputString))

   return inputString

inputString = "Simplilearn"

print("String before reversal is: ", inputString)

print("String after reversal is: ", reverseString(inputString))

The program created above has a function that takes the input string as a parameter, and then you have used the reversed() method on the input string to return a reversed iterator or object. Then the program has used the .join() method with an empty separator to join the elements of the reversed iterator. This will give you the final reversed string. Let’s run the program and see the output.

Reverse multiple strings in Python

String Slicing to Reverse a String in Python

You can also use another tricky method to reverse a string in Python. This is by far the easiest and shortest method to reverse a string. You will use the extended slice technique by giving a step value as -1 with no start and stop values. 

The general syntax of the extended slice in Python is [start, stop, step]. If you don’t mention any start value, it defaults to 0, which is the beginning of the string. And if you don’t mention any stop value, it defaults to the end of the string. And -1 as a step value means that the string needs to be traversed in the reversed manner. So, it begins from the end of the string and stops at the start, giving us a reversed string.

Let’s check out the program below.

def reverseString(inputString):

   inputString = inputString[::-1]

   return inputString

inputString = "Welcome to Simplilearn"

print("String before reversal is: ", inputString)

print("String after reversal is: ", reverseString(inputString))

In the above program, you have used the string slicing with a step value -1 to reverse the string. Let’s verify the output.

Reverse multiple strings in Python

You can see that you have successfully reversed the string using extended string slicing.

Reversing a String by Converting it into a List

Another way of reversing a string is by first converting it to a list and then reverse the list using the list.reverse() method. You can then use the list.join() method to convert it back to the string. However, this method is the least efficient one. Let’s look at the below program.

def reverseString(inputString):

   myList = list(inputString)

   myList.reverse()

   inputString = "".join(myList)

   return inputString

inputString = "Welcome to Simplilearn"

print("String before reversal is: ", inputString)

print("String after reversal is: ", reverseString(inputString))

Here, you can see that inside the reverseString function, you have first converted the string to a list, then you saw the usage of the list.reverse() method to reverse the list and then joined it back using the list.join() method. Let’s verify the output.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

In this comprehensive guide, you looked into several methods to reverse a string in Python, including practical examples of each of them. You saw how to use stacks, for-loops, recursion, slicing, reversed() method, and even convert it to a list to reverse a string. However, the most efficient, quick, and easy-to-remember is the string slicing method, which is simply a one-liner.

If you are looking to enhance your career and become in Python, you might want to explore Simplilearn’s Python Certification Course. This course offers a comprehensive curriculum that will help you learn the fundamentals of python and more beyond topics including data operations, shell scripting, conditional statements, Django and more. This program is the ideal starting point for anybody looking to master the Python language today.

We hope that you enjoyed this article and you are now well-equipped with multiple ways to reverse a string in Python. If you have any questions for us, leave them in the comments section of this article. Our experts will get back to you on the same, soon!

Happy Learning!

About the Author

Reverse multiple strings in Python
Ravikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

How do you reverse a list of strings in Python?

In Python, you can reverse the items of lists ( list ) with using reverse() , reversed() , and slicing. If you want to reverse strings ( str ) and tuples ( tuple ), use reversed() or slice.

Does Reverse () work on strings Python?

Strings are immutable in Python, so reversing a given string in place isn't possible.

How do you reverse 1234 in Python?

Python Program to reverse the digits of a number.
# Program to reverse the digits of a number literally..
# Input = 1234..
# Output = 4321..
num = int(input("Enter a number: \n")).
reverse = 0..

How do you reverse all words in a list Python?

Algorithm.
Initialize the string..
Split the string on space and store the resultant list in a variable called words..
Reverse the list words using reversed function..
Convert the result to list..