Use extended slice notation s[::-1]—which executes at the C level in CPython in $O(n)$ time with minimal overhead, making it both the fastest and most idiomatic way to reverse a string in Python.
Basic Example
text = "Python 3.12"
# 1. Fastest & most Pythonic: Extended slice notation [::-1]
reversed_text = text[::-1]
print(reversed_text) # Output: "21.3 nohtyP"
# 2. Alternative: "".join(reversed(text)) (slower due to iterator + join overhead)
reversed_via_iter = "".join(reversed(text))
print(reversed_via_iter) # Output: "21.3 nohtyP"
Key Details & Edge Cases
- Why
s[::-1]is the fastest method:- In CPython,
s[::-1]allocates the exact target buffer size upfront in C and copies characters backward in a single tight C loop (unicode_slice). - By contrast,
"".join(reversed(s))creates a Python iterator object, yields one single-characterstrobject per character, and scans the sequence twice instr.join(), making it roughly 3× to 6× slower thans[::-1].
- In CPython,
- Immutability (
strcannot be reversed in-place):- Python strings are immutable, so
s.reverse()does not exist (calling it raisesAttributeError: 'str' object has no attribute 'reverse'). Every reversal method returns a newstrobject in $O(n)$ space.
- Python strings are immutable, so
- Unicode grapheme clusters, emojis, and combining accents:
- Both
s[::-1]andreversed(s)reverse Unicode code points, not visual grapheme clusters. - For standard ASCII or precomposed characters (
"café"$\rightarrow$"éfac"), this works as expected. However, for decomposed combining marks ("e\u0301") or multi-code-point emojis ("👨👩👧👦", flag emojis"🇵🇰"), code-point reversal splits the sequence and corrupts the glyph. If you need grapheme-aware reversal, use the third-partyregexmodule’s\Xgrapheme matcher ("".join(reversed(regex.findall(r"\X", s)))).
- Both
- Palindrome check shortcut: Checking
s == s[::-1]is the fastest single-expression palindrome check for moderate-length strings (though a manual two-pointer loop can exit early in $O(1)$ best-case time if the first and last characters mismatch on multi-megabyte strings).
Comparison of String Reversal Methods in Python
| Method | Syntax | Time / Space | Relative Speed (CPython) | Best Used When |
|---|---|---|---|---|
Extended Slice ([::-1]) |
s[::-1] |
$O(n)$ / $O(n)$ | Fastest (1.0× baseline) | Reversing any standard string cleanly and idiomatically. |
"".join(reversed(s)) |
"".join(reversed(s)) |
$O(n)$ / $O(n)$ | ~3–6× slower | You only need a lazy reverse iterator (reversed(s)) without materializing the full string. |
| Grapheme-Cluster Regex | "".join(reversed(regex.findall(r"\X", s))) |
$O(n)$ / $O(n)$ | ~20–50× slower (3rd-party regex) |
Reversing text containing complex emojis, flags, or combining diacritics without breaking glyphs. |
| Manual Loop / Comprehension | "".join(s[i] for i in range(len(s)-1, -1, -1)) |
$O(n)$ / $O(n)$ | ~10–15× slower | Never—strictly slower and less readable than s[::-1]. |
You must log in or register to comment.
