Python: 5 Ways to Reverse a String

Updated: May 24, 2023 By: Wolf Post a comment

When writing code with Python, there might be cases where you need to reverse a string, such as when you want to check if a string is a palindrome ( a word or phrase that is the same when read forward or backward) or perform some encryption or decryption algorithms. This succinct, practical article will show you several different approaches to reversing a given string in Python.

Using the slice notation with a step of -1

This approach uses the slice notation [start:end:step] to reverse the string by specifying a step of -1.

Example:

text = "ABCDE 12345"
reversed_text = text[::-1]

print(reversed_text)

Output:

54321 EDCBA

Using the reversed() function and the join() method

The reversed() function takes a string and returns an iterator that traverses the string in reverse order. From the resulting iterator, you can use ''.join() to obtain the reversed string.

Example:

text = "Sling Academy"
reversed_text = ''.join(reversed(text))

print(reversed_text)

Output:

ymedacA gnilS

Using a for…in loop

In this approach, we will use a for...in loop to iterate over each character in the original string and builds the reversed string by prepending each character.

A code example is worth more than a thousand words:

text = "ABCDEFGH"
reversed_text = ''
for char in text:
    reversed_text = char + reversed_text

print(reversed_text)

Output:

HGFEDCBA

Using recursion

In the example below, we will define a recursive function named reversed_string to reverse an input string by appending the last character to the reversed substring of the remaining characters.

Example:

def reverse_string(text):
    if len(text) <= 1:
        return text
    return reverse_string(text[1:]) + text[0]

reversed_text = reverse_string("Welcome to Sling Academy!")

print(reversed_text)

Output:

!ymedacA gnilS ot emocleW

Using the list.reverse() method

In this approach, we will convert the original string into a list, then reverse the list by using the reverse() method. Finally, we will convert it back to a string with the help of the str.join() method.

The code:

text = "Elden Ring is a great game!"
char_list = list(text)
char_list.reverse()
reversed_text = ''.join(char_list)

print(reversed_text)

Output:

!emag taerg a si gniR nedlE