Python Example - Reverse a string

This tutorial explains various methods to reverse a string in Python with code examples.

For instance, if the string is hello, the result should be olleh.

Python Reverse a String example

There are multiple ways to reverse a string, each with its own pros and cons.

  • use slice notation

String slice notation has the syntax string[start:stop:step] and returns a part of the string.

str="hello";

print(str[::-1]);

In this case, start and stop are ignored, and step is set to -1. This moves from right to left by 1 character, resulting in the reversed string.

Pros:

Easy, readable, and simple. Fast performance. Cons: Does not work well with Unicode characters.

print("U+00EA"[::-1]) # AE00+U
  • Using the reversed Function

The reversed function converts the string into an object of a reversed string, which is then converted back into a string by joining (using the join function) with an empty string.

str="hello";

print("".join(reversed(str)))

This approach is slower, as the join function builds a new string and concatenates the characters in reverse order.

  • Using a Custom Recursive Function

Write a custom recursive function. The function calls itself until a condition is met to break the execution:

  • Check if the string length is 1 character, and return it.
  • Join the last character by calling the reverse of the remaining string.
str="hello";
def reverseString(str):
    if len(str) == 1:
        return str

    return str[-1] + reverseString(str[:-1])
print(reverseString(str));

Cons:

This recursive approach works for small strings, but for larger strings, it may throw a RecursionError: maximum recursion depth exceeded while calling a Python object. Therefore, it is not advisable to use this approach for larger strings.