Reverse String In Python (6 Ways)


Let's learn how to reverse string in Python using multiple different ways that are very efficient and easy to understand.

Python does not have any built-in function to reverse a string. We have to use some other way to reverse strings.

Reversing a string is a very common task in computer programming. When a string is reversed, the order of the characters is reversed. For example, the string 'abcde' is reversed to 'edcba'.

    Table Of Contents

  1. Reverse String In Python using For Loop
  2. Reverse String In Python using While Loop
  3. Reverse String In Python using Recursion
  4. Reverse String using List Comprehension
  5. Reverse String using Extended Slice⭐️🥇
  6. Reverse String using Stack
  7. Conclusion

reverse string in python

1. Reverse String In Python using For Loop

Python for loop can be used to solve versatile problems. And this can also be used to reverse a string.

To get the reverse of a string, we will create a new empty string and then use a for loop to add each character of the original string to the new string in reverse order.

The code to reverse a string using for loop is as follows:

  • Method 2
str = "TutorialsTonight"
reverse_str = ""

# loop from last character to first character
for i in range(len(str) - 1, -1, -1):
    reverse_str += str[i]

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")
str = "TutorialsTonight"
reverse_str = ""

# loop from first character to last character
# but access the string from the other end
for i in range(len(str)):
    reverse_str += str[len(str) - i - 1]

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")

Output:

Original String: TutorialsTonight
Reversed String: thginoTslairotuT

2. Reverse String In Python using While Loop

Python while loop can also be used to reverse a string.

The code to reverse a string using the while loop is as follows:

  • Method 2
str = "TutorialsTonight"
reverse_str = ""

# using while loop
len = len(str)
while len > 0:
    reverse_str += str[len - 1]
    len -= 1

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")
str = "TutorialsTonight"
reverse_str = ""

while len(str) > 0:
    reverse_str += str[len(str) - 1]
    str = str[:-1]

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")

Output:

Original String: TutorialsTonight
Reversed String: thginoTslairotuT

3. Reverse String In Python using Recursion

Recursion is a very useful concept in computer programming. It can also be used to reverse a string.

The code to reverse a string using recursion is as follows:

  • Method 2
str = "TutorialsTonight"

# using recursion
def reverse_string(str):
    if len(str) == 1:
        return str
    else:
        # last character first
        return str[-1] + reverse_string(str[:-1])

print(f"Reverse String using Recursion: {reverse_string(str)}")
str = "TutorialsTonight"

# using recursion
def reverse_string(str):
    if len(str) == 1:
        return str
    else:
        # first character last
        return reverse_string(str[1:]) + str[0]

print(f"Reverse String using Recursion: {reverse_string(str)}")

Output:

Reverse String using Recursion: ehtretniTslautroT

4. Reverse String using List Comprehension

List comprehension is a concept in Python that provides a shorter way to create a list. Let's see how it can be used to reverse a string.

Using this concept we will convert string to list, reverse the order of the list and then convert list to string to get the reverse string.

Here is the program to reverse a string using list comprehension.

  • Method 2
str = "TutorialsTonight"

# using list comprehension

# converting string to list (character reversed)
reverse_str_list = [str[i] for i in range(len(str)-1, -1, -1)]
# converting list to string
reverse_str = "".join(reverse_str_list)

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")
str = "TutorialsTonight"

# using list comprehension

# converting string to list
str_list = [char for char in str]
# reverse the list
str_list.reverse()
# converting list to string
reverse_str = "".join(str_list)

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")

Output:

Original String: TutorialsTonight
Reversed String: thginoTslairotuT

5. Reverse String using Extended Slice

You can slice a string in Python by using str[start:end:step]. We can use this to reverse a string.

Skip start and end values this way Python chooses start as 0 and end as -1. Give step value as -1 so that it reverses the string.

Here is the code for this.

  • Method 2
str = "TutorialsTonight"

# using extended slice
reverse_str = str[::-1]

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")
str = "TutorialsTonight"

# using extended slice
reverse_str = str[-1::-1]

print(f"Original String: {str}")
print(f"Reversed String: {reverse_str}")

Output:

Original String: TutorialsTonight
Reversed String: thginoTslairotuT

6. Reverse String using Stack

Stack is a data structure in which the last element added is the first element to be removed. It is a LIFO data structure.

Using the concept of the stack we can reverse a string.

Here is the code to reverse a string using a stack.

# create an empty stack
def createStack():
	stack = []
	return stack

# size of the stack
def size(stack):
	return len(stack)

# check if the stack is empty
def isEmpty(stack):
	if size(stack) == 0:
		return True

# add an item to stack
def push(stack, item):
	stack.append(item)

# Function to pop topmost element from the stack
def pop(stack):
	if isEmpty(stack):
		return
	return stack.pop()

# function to reverse a string
def reverse(string):
	str_len = len(string)

	# Create an empty stack
	stack = createStack()

	# Push all characters of string to stack
	for i in range(str_len):
		push(stack, string[i])

	# empty string to store reverse string
	reverse_str = ""

	# pop character from the stack and add to an empty string
	for i in range(str_len):
		reverse_str += pop(stack)

	return reverse_str

# Driver code --------------------------
str = "TutorialsTonight"
print(f"Reverse string(using stack): {reverse(str)}")

Output:

Reverse string(using stack): ehtretniTslautroT

Performance Comparison Of All Methods

Let's see which one of above methods is the fastest.

Following program executes each of above function for 100000 times for same input and prints the execution time of each method.

To test the performance we have made Python function from the above program and executed it 100000 times. Here is the code.

import time
# run performance test for each methods

# Method 1:
def reverseStr1(str):
    reverse_str = ""
    for i in range(len(str) - 1, -1, -1):
        reverse_str += str[i]
    return reverse_str

start = time.time()
for i in range(100000):
    reverseStr1("hello")
end = time.time()

print(f"Time taken by method 1: {(end - start) * 1000}ms")

# Method 2:
def reverseStr2(str):
    reverse_str = ""
    # using while loop
    length = len(str)
    while length > 0:
        reverse_str += str[length - 1]
        length -= 1
    return reverse_str

start = time.time()
for i in range(100000):
    reverseStr2("hello")
end = time.time()

print(f"Time taken by method 2: {(end - start) * 1000}ms")

# Method 3:
def reverseStr3(str):
    if len(str) == 1:
        return str
    else:
        # last character first
        return str[-1] + reverseStr3(str[:-1])

start = time.time()
for i in range(100000):
    reverseStr3("hello")
end = time.time()

print(f"Time taken by method 3: {(end - start) * 1000}ms")

# Method 4:
def reverseStr4(str):
    reverse_str_list = [str[i] for i in range(len(str)-1, -1, -1)]
    # converting list to string
    reverse_str = "".join(reverse_str_list)
    return reverse_str

start = time.time()
for i in range(100000):
    reverseStr4("hello")
end = time.time()

print(f"Time taken by method 4: {(end - start) * 1000}ms")

# Method 5:
def reverseStr5(str):
    return str[::-1]

start = time.time()
for i in range(100000):
    reverseStr5("hello")
end = time.time()

print(f"Time taken by method 5: {(end - start) * 1000}ms")

# Method 6:
def reverseStr6(str):
    arr = list(str)
    length = len(arr)

    while(length):
        arr.insert(0, arr.pop())
        length -= 1
    return "".join(arr)

start = time.time()
for i in range(100000):
    reverseStr6("hello")
end = time.time()

print(f"Time taken by method 6: {(end - start) * 1000}ms")

Output:

Time taken by method 1: 74.01609420776367ms
Time taken by method 2: 70.11675834655762ms
Time taken by method 3: 108.76584053039551ms
Time taken by method 4: 87.30673789978027ms
Time taken by method 5: 15.645503997802734ms
Time taken by method 6: 132.80391693115234ms

Note: Output of above code different everytime because of many factors but will always be close to this.

So from above output we can say that method 5 is the fastest which is Extended slice.


Conclusion

We have seen 6 different ways to reverse a string in Python. Now depending on the requirements and situations, we can use any of these methods.

The fastest of all the above methods is Extended Slice Method⭐️🥇.