Explain Codes LogoExplain Codes Logo

How do I reverse a string in Python?

python
string-manipulation
slicing
performance
Nikita BarsukovbyNikita Barsukov·Aug 8, 2024
TLDR

Reverse a string in Python with the slice trick [::-1]. It's as simple as this:

print('coding'[::-1]) # Outputs: 'gnidoc'

No extra variables or convoluted logic needed. Efficient, elegant, and quick.

Understanding string slicing

Python slicing uses the format start:stop:step, allowing powerful manipulation of strings. Employ a negative step (-1) to reverse a sequence. With start and stop omitted, it operates on the entire string.

# Beer gone in reverse! "🍺"[::-1] reversed_beer = my_string[::-1]

Slicing allows precise results. Need only a portion? Specify start and stop:

# Hey there, opposite day! "hey there"[5:2:-1] opposite_day = my_string[5:2:-1]

Other ways to reverse strings

While [::-1] is quick and "pythonic", other methods might improve readability or address specific situations:

Using reversed() function

reversed() gives an iterator in reversed order. Use ''.join() to get a string:

# Turtles, but in reverse reversed_turtles = ''.join(reversed(my_string)) # "Shell yeah!" reversed

Encapsulating slice in function

A quick slice muffled inside a function boosts readability and reuse:

# Gift wrap the magic! def reversible_string(a_string): return a_string[::-1] print(reversible_string('lap')) # Should print... take a guess!

Functions: because some operations love to play hard-to-get.

join with list comprehension

Blend join() and a list comprehension for adaptable handling:

# Let's do-it-yourself reversed_diy = ''.join([char for char in reversed(my_string)]) # Craftsman mode: ON

Master slice notation

Mastering slice notation is as crucial as avoiding pineapples on pizza. With negative indexes, you can reference from the string's end:

# Detective mode, last three clues, in reverse! last_three = my_string[:-4:-1]

Remember: stop is exclusive; start is inclusive. Python follows a strict bouncer policy.

Unicode and emojis

Unicode strings with emojis or compound characters? Pfft, grapheme library's got you covered:

import grapheme # Make emojis moonwalk reversed_unicode_str = grapheme[::-1](my_string) # Even emojis have a backside

Speed is key

Performance mattering more than a pizza delivery? Benchmark the options:

import timeit # Ready, set, go! slicing_time = timeit.timeit(lambda: my_string[::-1], number=1000) reversed_time = timeit.timeit(lambda: ''.join(reversed(my_string)), number=1000) print(f"Slicing: {slicing_time}, Reversed: {reversed_time}") # Let's see who wins

Strings are immutable, remember?

Python strings don't evolve like Pokémon. Avoid character-by-character construction — it's the Snorlax of string operations.