How to reverse a string in Python? (code examples)
The simplest and most Pythonic way to reverse a string in Python is slicing with [::-1], which is fast, readable, works on any sequence, handles Unicode correctly, and safely manages edge cases like empty or single-character strings.

Use slicing with [::-1] — the simplest and most Pythonic way
Slicing with [::-1] is the go-to method for reversing strings in Python. It’s fast, readable, and works on any sequence type (strings, tuples, lists). Under the hood, it creates a new string by stepping backward through the original.
Why it’s preferred: no imports, no loops, no function calls — just one clean expression.
-
"hello"[::-1]→"olleh" - Works identically on Unicode:
"café"[::-1]→"éfac"(no encoding gotchas) - Empty or single-character strings behave correctly:
""[::-1]→"","x"[::-1]→"x"
Avoid reversed() join() unless you need iterator semantics
reversed() returns an iterator, not a string — so you must combine it with ''.join(). It’s valid, but less direct than slicing.
This pattern matters only if you’re already working with iterators or want lazy evaluation (rare for small strings).
text = "world" reversed_text = ''.join(reversed(text)) # → "dlrow"
- Don’t do
str(reversed("abc"))— that gives"<reversed object at>"</reversed> - No performance benefit over slicing for typical use; slicing is faster for strings
- Only consider this if you’re chaining with other iterator operations (e.g.,
itertools.islice(reversed(s), 5))
Don’t use recursion or manual loops — they’re unnecessary and error-prone
You’ll see recursive or while-loop examples online, especially in learning contexts. In real code, they add complexity without benefit — and risk RecursionError or off-by-one bugs.
- Recursive version fails on long strings:
len("a" * 10000)triggersRecursionError - Manual index loops like
for i in range(len(s)-1, -1, -1): result = s[i]are O(n²) due to string immutability — avoid repeated= - No gain in clarity, readability, or control — slicing does exactly what you need
Watch out for mutable vs immutable confusion when “reversing in place”
Strings are immutable in Python — there’s no .reverse() method like on lists. If you try "hello".reverse(), you’ll get AttributeError: 'str' object has no attribute 'reverse'.
If you actually need in-place reversal (e.g., for a list of characters), convert first:
chars = list("hello")
chars.reverse() # now in-place
result = ''.join(chars) # → "olleh"
- This two-step dance is only useful if you’re doing multiple mutations on the character sequence
- For pure reversal, it’s extra work — stick with
[::-1] - Confusing
list.reverse()(in-place) withreversed()(iterator) is a common source of bugs
Slicing with [::-1] is almost always the right choice — but remember it always returns a new string, never modifies the original. That immutability is fundamental, not a limitation to work around.
The above is the detailed content of How to reverse a string in Python? (code examples). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20519
7
13632
4
Solve the error of multidict build failure when installing Python package
Mar 08, 2026 am 02:51 AM
When installing libraries that depend on multidict in Python, such as aiohttp or discord.py, users may encounter the error "ERROR: Could not build wheels for multidict". This is usually due to the lack of the necessary C/C compiler or build tools, preventing pip from successfully compiling multidict's C extension from source. This article will provide a series of solutions, including installing system build tools, managing Python versions, and using virtual environments, to help developers effectively solve this problem.
How to find the sum of 5 numbers using Python's for loop
Mar 10, 2026 pm 12:48 PM
This article explains in detail how to use a for loop to read 5 integers from user input and add them up, provide a concise and readable standard writing method, and compare efficient alternatives to built-in functions.
How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction
Mar 13, 2026 am 11:54 AM
The essence of zip is zipper pairing, which packs multiple iterable objects into tuples by position and does not automatically unpack the dictionary. When passing in a dictionary, its keys are traversed by default. You need to explicitly use the keys()/values()/items() view to correctly participate in parallel traversal.
How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation
Mar 13, 2026 pm 12:18 PM
Multi-dimensional classification histograms need to manually calculate the x position and call plt.bar hierarchically; when stacking, bottom must be used to accumulate height, and xticks and ylim must be explicitly set (bottom=0); avoid mixing stacked=True and seaborn, and colors should be dynamically generated and strictly match the layer sequence.
Using Python Pandas to process Excel non-standard format data: cross-row cell merging techniques
Mar 06, 2026 am 11:48 AM
This article details how to use the Python Pandas library to automate processing of non-standard data formats in Excel spreadsheets, specifically for those situations where the data content spans multiple consecutive rows but logically belongs to the same cell. By iteratively processing row pairs and conditionally merging data in specified columns, the information originally scattered in two rows is integrated into a list within a single cell, thereby converting non-standard format data into a standardized table structure for subsequent analysis and processing.
Python set intersection optimization_large data volume set operation skills
Mar 13, 2026 pm 12:36 PM
The key to optimizing Python set intersection performance is to use the minimum set as the left operand, avoid implicit conversion, block processing and cache incremental updates. Priority should be given to using min(...,key=len) to select the smallest set, disabling multi-parameter intersection(), using frozenset or bloom filters to reduce memory, and using lru_cache to cache results in high-frequency scenarios.
How Python manages dependencies_Comparison between pip and poetry
Mar 12, 2026 pm 04:21 PM
pip is suitable for simple projects, which only install packages and do not isolate the environment; poetry is a modern tool that automatically manages dependencies, virtual environments and version locking. Use pip requirements.txt for small projects, and poetry is recommended for medium and large projects. The two cannot be mixed in the same project.
How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse
Mar 12, 2026 pm 05:48 PM
Use scipy.sparse.coo_matrix instead of a dictionary because the bottom layer uses row/col/data three-array to efficiently support operations; the structure needs to be deduplicated, converted to csr/csc and then calculated; save_npz is preferred for saving; operations such as slicing must use csr/csc format.





