Skip to content

Reverse String in Python

[

Reverse Strings in Python: reversed(), Slicing, and More

When working with Python strings, you may find the need to reverse them. Python offers several tools and techniques that can help you achieve this easily and efficiently. By learning how to reverse strings in Python, you can enhance your skills as a Python developer.

In this tutorial, you will learn how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Reverse strings manually using iteration and recursion
  • Iterate through strings in reverse order
  • Sort strings in reverse order using sorted()

To fully understand this tutorial, you should have knowledge of strings, for and while loops, and recursion.

Reversing Strings With Core Python Tools

Sometimes you may need to reverse a string in Python. For example, if you have a string like “ABCDEF” and want to reverse it to “FEDCBA”, Python provides tools to help you accomplish this task efficiently.

Since strings are immutable in Python, you cannot reverse them in place. Instead, you need to create reversed copies of strings to achieve the desired result.

Python offers two straightforward ways to reverse strings. First, you can use slicing to directly generate a copy of a string in reverse order. Second, you can use the built-in function reversed() to create an iterator that yields the characters of a string in reverse order.

Reversing Strings Through Slicing

Slicing is a powerful technique that allows you to extract items from a sequence by specifying the integer indices of the items you want. With slicing, you can easily generate a copy of a string in reverse order.

Here’s an example that demonstrates how to reverse a string using slicing:

original_string = "ABCDEF"
reversed_string = original_string[::-1]
print(reversed_string)

Output:

FEDCBA

In the above example, [::-1] is the slicing operation that reverses the string original_string. The resulting string is stored in the variable reversed_string and printed to the console.

Reversing Strings With .join() and reversed()

Another way to reverse a string is by using the .join() method in combination with the reversed() function.

Here’s an example that demonstrates this approach:

original_string = "ABCDEF"
reversed_string = ''.join(reversed(original_string))
print(reversed_string)

Output:

FEDCBA

In this example, the reversed() function returns an iterator that yields the characters of original_string in reverse order. The "".join() method is then used to join these characters into a single string. Finally, the reversed string is stored in the variable reversed_string and printed to the console.

Generating Reversed Strings by Hand

In some situations, you may want to reverse strings manually without using the built-in functions or slicing. This can be achieved using iteration or recursion.

Reversing Strings in a Loop

One way to reverse a string in a loop is by iterating through it from the last character to the first and appending each character to a new string.

Here’s an example:

original_string = "ABCDEF"
reversed_string = ""
for char in original_string:
reversed_string = char + reversed_string
print(reversed_string)

Output:

FEDCBA

In this example, the loop iterates through each character in the original_string and appends it to the beginning of the reversed_string. This effectively reverses the original string.

Reversing Strings With Recursion

Another approach to reversing strings is by using recursion. In this method, a recursive function is defined to handle the reversal process.

Here’s an example:

def reverse_string(string):
if len(string) <= 1:
return string
return reverse_string(string[1:]) + string[0]
original_string = "ABCDEF"
reversed_string = reverse_string(original_string)
print(reversed_string)

Output:

FEDCBA

In this example, the reverse_string() function takes a string as input. If the length of the string is less than or equal to 1, it returns the string as is. Otherwise, it recursively calls itself with the string sliced from the second character onwards (string[1:]) and concatenates it with the first character of the string (string[0]).

Iterating Through Strings in Reverse

Python provides built-in functions and operators to iterate through strings in reverse order.

The reversed() Built-in Function

The reversed() function returns an iterator that yields the characters of a string in reverse order. By using a loop or a comprehension, you can easily iterate over the reversed string.

Here’s an example:

original_string = "ABCDEF"
for char in reversed(original_string):
print(char)

Output:

F
E
D
C
B
A

In this example, the reversed() function is used to create an iterator that yields the characters of original_string in reverse order. The loop then iterates over each character and prints it to the console.

The Slicing Operator, [::-1]

Another way to iterate through a string in reverse order is by using slicing with the [::-1] syntax.

Here’s an example:

original_string = "ABCDEF"
for char in original_string[::-1]:
print(char)

Output:

F
E
D
C
B
A

In this example, the [::-1] slicing operator is used to create a reversed copy of the original_string. The loop then iterates over each character of the reversed string and prints it to the console.

Creating a Custom Reversible String

In Python, you can create custom objects that behave like strings and can be reversed using the core Python tools.

Here’s an example of a custom ReversibleString class:

class ReversibleString:
def __init__(self, string):
self.string = string
def reverse(self):
return self.string[::-1]
def __repr__(self):
return f"ReversibleString('{self.string}')"
original_string = ReversibleString("ABCDEF")
reversed_string = original_string.reverse()
print(reversed_string)

Output:

FEDCBA

In this example, the ReversibleString class is defined with a string attribute and a reverse() method. The reverse() method uses slicing to create a reversed copy of the string. The __repr__() method is implemented to provide a meaningful string representation of the object. Finally, an instance of the ReversibleString class is created with the original_string and the reverse() method is called.

Sorting Python Strings in Reverse Order

Python provides the sorted() function that can be used to sort strings in reverse order.

Here’s an example:

original_string = "ABCDEF"
sorted_string = sorted(original_string, reverse=True)
reversed_string = ''.join(sorted_string)
print(reversed_string)

Output:

FEDCBA

In this example, the sorted() function is used to sort the characters of original_string in reverse order. The reverse=True argument ensures the reverse sorting. The sorted characters are then joined into a single string using the "".join() method, resulting in the reversed string.

Conclusion

Reversing strings in Python can be easily accomplished using the core Python tools such as slicing, reversed(), and iteration. You can also reverse strings manually through loops or recursion. Additionally, Python provides functionality to sort strings in reverse order. By mastering these techniques, you can efficiently work with reversed strings and enhance your skills as a Python developer.

Remember to practice these methods with different strings to gain proficiency and confidence in working with reversed strings in Python.