Reverse a string in Python - Different techniques Explained


What is a string in Python?

In Python, a string is a series of characters enclosed in quotes. A string can be a combination of digits, symbols, and white spaces, and they can be of any length.

Example -
some_string = "Code Part Time"

Programming languages such as C++, Java, and JavaScript have a direct built-in function to reverse a string called reverse(), which is invoked on a string to reverse it. 

Unfortunately, Python doesn't have a built-in function to reverse a string. However, we can use several other methods to reverse a string in Python. In this article, we will discuss several ways to achieve it.

NOTE: In Python, strings are immutable, which means that once a string is created, its content cannot be changed.

Now let us look into Python techniques to reverse a string with examples.

Using a Loop

We can reverse a string by using a while loop or for loop. Reversing is done by iterating over the characters of a string in reverse ordering and then appending the characters of the string to a new string.

Example 1 - Reverse a string using the While loop in Python

Below is the Python code to reverse a string using a While loop.

some_string = "Code Part Time"   #intial string
reversed_string = ""  
index = len(some_string) - 1

while index >= 0:
    reversed_string += some_string[index]   
    index -= 1

print(reversed_string)   #reversed string

The Output will be -

emiT traP edoC

Explanation -

  • In the above code, we initialized an empty string 'reversed_string' for storing our answer.
  • Then we set the 'index' variable equal to the length of the original string(some_string) minus one.
  • Then we used the while loop to iterate over each character of 'some_string' in reverse order and appending each character to the 'reversed_string' variable.

Example 2 - Reverse a string using the For loop in Python

Below is the Python code to reverse a string using a For loop.

some_string = "Code Part Time"   #intial string
reversed_string = ""  
index = len(some_string) - 1

reversed_string = ''
for char in some_string:
    reversed_string = char + reversed_string  # appending characters in reverse order

print(reversed_string)   #reversed string

The Output will be -

emiT traP edoC

Explanation -

  • In the above code, we initialized an empty string 'reversed_string' for storing our answer.
  • Then we used the for loop to iterate over each character of 'some_string' in reverse order and appended each character in reverse order to the 'reversed_string' variable.

Following is the performance of reversing a string in Python using the While loop and For loop.

Time Complexity: 0(n)
Here n represents the length of the input string.

Space Complexity: 0(1)
It requires the same amount of space regardless of the input size.

Using a stack

To reverse a string using a stack in Python, we need to -

  • First, we must create an empty stack.
  • Then we need to push each character of the string onto the stack.
  • And lastly, we pop each character off the stack and append it to a new string.

NOTE: Stack is a Data Structure that works on the principle of LIFO(last-in-first-out).

Example - Reverse a string using a stack in Python

Below is the Python code to reverse a string using a stack.

#Function to reverse a string using stack
def reverse_string_using_stack(string):
    stack = []  #an empty stack
    for char in string:
        stack.append(char)

    reversed_string = ""
    length_of_stack = len(stack)  #length of stack
    while length_of_stack > 0:
        reversed_string += stack.pop()  #pop each character of string from stack
        length_of_stack -= 1

    return reversed_string

#Driver code
some_string = "Code Part Time"
print(reverse_string_using_stack(some_string))

The Output will be -

emiT traP edoC

Explanation -

  • In the above code, we create an empty stack by initializing the stack as a list.
  • Using the append method, we iterate through each input string(some_string) character and push every character into the stack.
  • Then we use the while loop and pop each character off the stack using the pop() method.
  • Lastly, we append each character to the reversed_string variable. Once the stack is empty, we return the reversed_string, which will be the reverse of the original string(some_string).

Following is the performance of reversing a string in Python using a stack -

Time Complexity: 0(n)
Space Complexity: 0(n)

Here n represents the length of the input string.

Using an extended slice method

A string can be reversed using slicing. The extended slice is by far the easiest method to reverse a string.

The extended slice method is a method for flexibly slicing sequences, such as strings and lists, using its syntax.

Syntax -
sequence[start:stop:step]

In the above syntax -

  • 'start' represents the slice's starting index (included).
  • 'stop' represents the ending index of the slice (excluded).
  • 'step' represents the step taken of the slice.

NOTE: By default, the start is  0, the stop is the length of the sequence, and the step is 1.

Example - Reverse a string using the extended slice method in Python

Below is the Python code to reverse a string using the extended slice method.

#function to reverse a string using the extended slice method
def reverse_string_using_slice(string):
    return string[::-1]

#Driver code
string = "Code Part Time"
reversed_string  = reverse_string_using_slice(string)
print(reversed_string)

The Output will be -

emiT traP edoC

Explanation -

  • In the above code, the syntax [::-1] means the string slicing starts at the end and ends at the beginning, with a step size of -1.
  • Hence, slicing this way gives us the original string's reverse.
  • In the example above, we pass the string "Code Part Time" to the function reverse_string_using_slice(), which returns the reversed string.

Following is the performance of reversing a string in Python using the extended slice method -

Time Complexity: 0(n)
Here n represents the length of the input string.

Space Complexity: 0(1)
It requires the same amount of space regardless of the input size.

Using join() and reversed() methods

Another exciting way to reverse a string in Python is using the join() and reversed() methods. Here is how we can achieve that -

  • Take an input string.
  • Then pass that string as an input parameter to the reversed() function. Python's reversed() function returns an iterator that traverses the specified sequence in reverse order.
  • Then lastly, use a list.join() function to convert the iterator object back to the string, giving us our reversed string.

Let's understand this method better with an example.

Example - Reverse a string using the join() and reversed() methods in Python

Below is the Python code to reverse a string using the join() and reversed() methods.

some_string = "Code Part Time"  # initial string

# using the reversed() function
reversed_iterator = reversed(some_string)

print(reversed_iterator)
print(type(reversed_iterator))

# using the join() function
reversed_string = ''.join(reversed_iterator)

print(reversed_string)

The Output will be -

<reversed object at 0x0000025729E3B9D0>
<class 'reversed'>
emiT traP edoC

Explanation -

  • In the above example, we use the reversed() function to create a reverse iterator object for the "Code Part Time" string.
  • Then we use the join() method to convert the reverse iterator object to a string. This gives us the reversed string in Python.

Following is the performance of reversing a string in Python using the join() and reversed() methods -

Time Complexity: 0(n)
Space Complexity: 0(n)

Here n represents the length of the input string. The time complexity is n because we create a string with 'n' elements to store the reversed string.

Using list.reverse() and join() methods

Another way to reverse a string in Python is using the list.reverse() and join() methods. Here is how we can achieve that -

  • Convert the input string to a list.
  • Then reverse the list using the built-in reverse function list.reverse().
  • Then lastly, use a list.join() function to convert it back to the string, giving us our reversed string.

Let's understand this method better with an example.

Example - Reverse a string using the list.reverse() and join() methods in Python

Below is the Python code to reverse a string using the list.reverse() and join() methods.

some_string = "Code Part Time"  # initial string

# converting the string to a list
list_string = list(some_string)

# using the list.reverse() function
list.reverse(list_string)
print(type(list_string))

# using the join() function
reversed_string = ''.join(list_string)
print(reversed_string)

The Output will be -

<class 'list'>
emiT traP edoC

Explanation -

  • In the above example, first, we convert the string to a list.
  • Then we reverse the order of elements in the list using the list.reverse() function.
  • Then we use the list.join() function to join the reversed list elements to a string. This gives us the reversed string in Python.

Following is the performance of reversing a string in Python using the list.reverse() and join() methods -

Time Complexity: 0(n)
Space Complexity: 0(n)

Here n represents the length of the input string.

Using recursion

The string in Python can also be reversed using recursion.

Recursion is a process where the function calls itself. We can reverse the string using recursion by finding the base cases and recursive cases.

Example - Reverse a string using the recursion in Python

Below is the Python code to reverse a string using recursion.

#function to reverse a string using recursion
def reverse_string_using_recursion(s):
    if len(s) == 0:   #base case
        return s
    else:
        #adding the first character of the string at the end after slicing
        return reverse_string_using_recursion(s[1:]) + s[0]

#Driver code
some_string = "Code Part Time"
reversed_string  = reverse_string_using_recursion(some_string)
print(reversed_string)

The Output will be -

emiT traP edoC

Explanation -

  • In the above example, the string is passed as an input parameter to a recursive function to reverse a string.
  • First, the function checks if the length of the string is zero, which is our base case. If it is, it simply returns the string which is already reversed.
  • If the length of a string is not equal to zero, in this case, the function calls itself recursively and slices the part of a string so that only the first character of a string is left and concatenates this first character to the end of the sliced string.

Following is the performance of reversing a string in Python using the recursion -

Time Complexity: 0(n)
Space Complexity: 0(n)

Here n represents the length of the input string. The time complexity is n because the function used 'n' recursion level on the call stack.

Conclusion

In this article, we discussed different techniques to reverse a string in Python, with the help of examples and looked at their complexities.

We saw how to reverse a string using the loops, stack, recursion, reversed(), list.reverse(), and slicing methods.

However, it is quick and easy to remember the string-slicing method, which is a one-liner solution.

Overall, the choice of method depends on the specific requirements of the task at hand.

I hope you found this article helpful.

Reverse a string in Python - Different techniques Explained

You may like to Explore -

Parse JSON String and JSON File in Python – Explained

startswith() Method – Python String – with Examples

Python maketrans() string method – Explained with Examples

Cheers!

Happy Coding.

About the Author

This article was authored by ANKIT SINGH. Verified by Rawnak.