How to Reverse a String in Python: Two Simple Methods
Reverse a string in Python with two methods: the slice idiom s[::-1] and an explicit while loop. Code, output, complexity, and the interview-grade choice.
Python does not have a built-in string.reverse() method, so reversing a string is one of those questions where the answer is either a one-character slice trick or a six-line loop, depending on who is asking. Both are O(n), both work correctly, and the choice between them is almost always a question of context, not performance.
This guide covers the slice method and the while-loop method, plus the reversed() built-in that most articles skip, with code you can paste into the Python REPL and the complexity analysis an interviewer will ask for.
The two methods, side by side
Before any code, here is the decision in one table.
| Concern | Slicing s[::-1] | While loop |
|---|---|---|
| Lines of code | 1 | 6 to 8 |
| Time complexity | O(n) | O(n) |
| Space complexity | O(n) (new string) | O(n) (new string) |
| Constant factor | Fast (C-level slice) | Slower (Python bytecode loop) |
| Readability | Idiomatic Python | Explicit, language-agnostic |
| Interview signal | ”I know Python idioms" | "I can show indexing logic” |
| Best for | Production code, scripts | Whiteboard interview, learning loops |
If you are writing code that ships, use the slice. If you are at a whiteboard with a recruiter watching, write the loop, then mention the slice exists.
Method 1: Slicing with [::-1]
Slicing in Python takes three optional arguments: start, stop, and step, written s[start:stop:step]. Leaving start and stop empty means “the whole sequence.” A step of -1 means “walk one element at a time, backwards.” Put them together and s[::-1] returns a new string with the characters in reverse order. The same slice syntax works on lists, tuples, and any other sequence type per the Python docs on common sequence operations.
Code
# Python program to reverse a string using slicing
s = input("Enter the string: ")
print("Reversed string:", s[::-1])
Example execution
-
Input:
FACE -
Output:
Reversed string: ECAF -
Input:
Prep -
Output:
Reversed string: perP
Why this is the default answer
- One line, no temporary variables, no off-by-one risk.
- Runs at C speed inside CPython because the slice is a built-in operation, not a Python-level loop.
- Works the same way on lists and tuples, so the idiom transfers.
The only reason not to use it: when the person asking the question wants to see you reason about indexes.
Method 2: A while loop
The loop version is the one a fresher interviewer will most often ask for, because slicing tells the interviewer nothing about whether you understand zero-based indexing. The algorithm is:
- Read the input string.
- Initialise an empty result string.
- Start an index at
len(s)and walk down to1. - At each step, append
s[index - 1]to the result. - Print the result.
Code
# Python program to reverse a string using a while loop
s = input("Enter the string: ")
reversed_string = ""
index = len(s)
while index > 0:
reversed_string += s[index - 1]
index -= 1
print("Reversed string:", reversed_string)
Example execution
- Input:
FACE - Output:
Reversed string: ECAF
Complexity, honestly
The loop is O(n) in time, but the constant factor is worse than slicing for two reasons. First, every iteration runs as Python bytecode, which is roughly 10x to 30x slower per operation than the C-level slice loop. Second, the reversed_string += s[index - 1] line builds up the result character by character. CPython can sometimes optimise this in place, but the safe assumption for interview analysis is that string concatenation in a loop is O(n) per append, giving O(n^2) worst case. The fix is to append to a list and join at the end:
chars = []
index = len(s)
while index > 0:
chars.append(s[index - 1])
index -= 1
reversed_string = "".join(chars)
That gets you back to O(n) total. Mentioning this trade-off out loud is the kind of thing that separates a freshers’ answer from a hire-grade answer.
The third method nobody mentions: reversed() plus join
The reversed() built-in returns an iterator that walks any sequence backwards. It does not return a string by itself, which is why most tutorials skip it. To get a string back, pipe it through ''.join():
s = "FACEPrep"
print("".join(reversed(s)))
# perPECAF
Why bother? Two reasons:
- It works on any reversible iterable, not just strings, so the same line reverses lists, tuples, and
rangeobjects. - It is more explicit about intent than
[::-1]for someone reading your code who has not memorised the slice idiom.
Performance sits between the slice and the bytecode loop. For most code the slice wins on terseness; reversed() wins on clarity in code reviews.
Common interview follow-ups
These are the questions that tend to come after “now reverse a string”:
Reverse the words in a sentence, not the characters
The trick is to split, reverse the list of words, then join. Use split() with no argument so consecutive whitespace collapses:
sentence = "how are you"
print(" ".join(sentence.split()[::-1]))
# you are how
If the interviewer asks you to reverse the characters within each word but keep word order, swap the position of the slice:
print(" ".join(word[::-1] for word in sentence.split()))
# woh era uoy
Can I reverse a string in place?
No. Strings in Python are immutable, so there is no in-place operation. Any reversal returns a new string and leaves the original untouched. If an interviewer asks for in-place reversal of a Python string, the correct answer is “you cannot, because strings are immutable; you can do it for a list of characters, then ''.join() the result.” That answer scores higher than silently writing a slice.
For the list-of-characters version:
chars = list("FACEPrep")
left, right = 0, len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
print("".join(chars))
# perPECAF
This is the two-pointer approach: O(n) time, O(1) extra space, and the version interviewers like to see for related questions like palindrome checks.
Unicode and emoji caveat
s[::-1] reverses Python’s internal code points, which is correct for plain ASCII and most Indic scripts at the code-point level. It breaks visibly for:
- Emoji that use ZWJ (zero-width joiner) sequences: a family emoji
👨👩👧is one user-visible character but multiple code points. - Skin-tone modifiers: 👍🏽 is two code points, base + modifier.
- Devanagari and Tamil grapheme clusters where a vowel sign attaches to the consonant before it.
For user-visible text reversal, use the regex module or the grapheme package on PyPI, both of which iterate by grapheme cluster instead of by code point.
Performance, with numbers
Rough timings on CPython 3.12, typical laptop, plain ASCII input:
- Hundred-thousand-character string,
s[::-1]: a few hundred microseconds. - Hundred-thousand-character string,
''.join(reversed(s)): a few milliseconds. - Hundred-thousand-character string, naive
+=while loop: tens to hundreds of milliseconds, depending on whether CPython’s append-in-place optimisation kicks in. - Interview-length string of five to fifty characters, all three: effectively instant.
The difference matters in two cases: hot loops on large strings, and the interview question that asks you which one is faster.
Where to go next
The natural next program after reversing a string is to sort a string in alphabetical order, which uses sorted(s) plus ''.join() and shares the same “strings are immutable, so you build a new one” pattern. If you are working through per-character problems, classifying a character as upper case, lower case, number, or special character is the canonical follow-up.
The slice trick is a 30-second answer; the loop is the answer that shows you can think about indexes. Both belong in your toolkit, and recognising which one the question wants is half the interview signal. If small Python idioms like [::-1] interest you, the next layer is using the same compact-syntax instinct on LLM-shaped problems: token slicing, prompt assembly, and output parsing. TinkerLLM is the ₹299 self-paced sandbox that takes you from “I can write a Python one-liner” to “I have shipped a small LLM tool.” Same instinct, different domain.
Primary sources
Frequently asked questions
What does [::-1] actually mean in Python?
It is a slice with three parts: start, stop, step. Leaving start and stop empty means 'the whole sequence'; the step of -1 means 'walk backwards one element at a time'. The same syntax works on lists and tuples, not just strings.
Is there a reverse() method for strings in Python?
No. Strings are immutable, so they do not have an in-place reverse() method like lists do. To reverse a string you create a new string using slicing, the reversed() built-in, or a loop. list.reverse() exists; str.reverse() does not.
Which is faster, slicing or a while loop?
Slicing is faster by a constant factor on CPython because the slice runs in compiled C, while the loop runs in Python bytecode. Both are O(n) in time. For a 1000-character string the slice is typically 10x to 30x faster, but for interview-style strings of length 5 to 50 the difference is invisible.
How do I reverse the words in a sentence, not the characters?
Use ' '.join(sentence.split()[::-1]). split() breaks on whitespace, [::-1] reverses the list of words, and ' '.join() puts them back together with single spaces. 'how are you' becomes 'you are how'.
Does s[::-1] work correctly with emoji or Unicode?
It reverses code points, which is correct for most scripts but breaks for emoji that use combining characters or skin-tone modifiers, and for grapheme clusters in scripts like Devanagari. For user-visible text reversal use the third-party regex or grapheme module, not bare slicing.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)