API Navigator Logo

How to Reverse a String in Python

Author: Newtum

This example shows the most common and Pythonic way to reverse a string using extended slice notation.

Using Slice Notation `[::-1]`

The easiest and fastest way to reverse a string in Python is to use the slice syntax `[::-1]`. This creates a reversed copy of the string without modifying the original.

original_string = "hello world"

# Reverse the string using slicing
reversed_string = original_string[::-1]

print(f"Original: {original_string}")
print(f"Reversed: {reversed_string}")

How Does it Work?

The slice `[start:stop:step]` selects a portion of the string. By omitting `start` and `stop` and providing a `step` of `-1`, you are telling Python to go through the whole string backwards, one character at a time.

Alternative Method: `"".join(reversed())`

Another way is to use the built-in `reversed()` function, which returns a reverse iterator, and then use `"".join()` to stitch the characters back into a string. This is generally more readable but slightly less performant than slicing.

original_string = "Python is fun"

# Use reversed() and join()
reversed_string = "".join(reversed(original_string))

print(f"Original: {original_string}")
print(f"Reversed: {reversed_string}")