Thuta Learning
Python
AdvancedProgrammingBeginner

Reverse String (Enhanced)

PythonLesson 5725 min

What you'll walk away with

  • Read text[::-1] in terms of start, stop and step
  • Know why reversed() needs join() to produce a string
  • Explain why the loop and recursive versions are O(n²) and why recursion hits a depth limit
  • Check palindromes while ignoring case, spaces and punctuation
  • Tell reversing code points apart from reversing the characters a user sees

Explain it simply

Explain it simply

Picture a string as beads on a thread, one character per bead. Reversing means threading a new string starting from the last bead, so "Python" becomes "nohtyP".

Python strings are immutable, so you can never flip the original in place; every technique builds a new string. What differs is speed and readability. There is also a catch: some beads are really two beads glued together, and if you reverse them separately the text comes out broken.

Problem → Why → Solution

The problem: correct for ASCII, broken for real text

A "mirror name" feature shows usernames backwards using text[::-1]. Tested with names like "Python" and "Sai", it works perfectly. After release, bug reports arrive: in names like "José" the accent lands on the wrong letter, Myanmar names turn into an unreadable scatter of vowel signs and consonants, and flag emoji turn into two separate letters.

No error is raised and every test passes, because the test data contained only plain English letters.

mirror.py
def mirror(name: str) -> str:
    return name[::-1]

print(mirror("Sai"))        # iaS   - fine
print(mirror("Jose\u0301")) # accent now sits before the 'e', not on it
# Myanmar text and emoji flags break in the same way

Why does this happen?

A Python string is a sequence of Unicode code points, and [::-1] reverses code points. A single character a user sees (a grapheme cluster) can be several code points: an e plus a combining accent, a Myanmar consonant plus vowel signs and medials, a flag made of two regional indicators. Reversing the parts separately breaks the combination.

Core concept: reading the slice, and four techniques

The full slice form is text[start:stop:step]. A negative step makes Python walk from the back towards the front, and leaving start and stop empty means "from one end all the way to the other", so [::-1] reads as "every element, from the last to the first". The same syntax works on lists and tuples, and [::-2] takes every second element from the back.

TechniqueCostWhen to use it
text[::-1]O(n), runs in CThe default choice
''.join(reversed(text))O(n)When chaining with iterators
result = ch + result loopO(n²)Only to understand the idea
RecursionO(n²), depth limitOnly to practise recursion

reversed() does not return a string

reversed(text) is an iterator that yields characters from the back; print(reversed(text)) shows only <reversed object ...>. "".join() glues those characters back into a single string.

Why the loop and recursion are slow

Strings are immutable, so every char + result builds a new string and copies all the characters so far. For n characters that is 1 + 2 + ... + n copies, which is O(n²). The recursive version's s[1:] copies too, and Python's default recursion limit of about 1000 means a string longer than that raises RecursionError.

Normalise before checking a palindrome

To treat "A man, a plan, a canal: Panama" as a palindrome, casefold() the text to ignore case and keep only isalnum() characters to drop spaces and punctuation. Only then compare cleaned == cleaned[::-1].

Lists, unlike strings, can flip in place

A list gives you three choices. items.reverse() flips the list in place, returns None and needs no extra memory. items[::-1] returns a new list. reversed(items) lets you loop backwards without copying anything. Strings are immutable, so only the last two ideas apply to them.

Mental model: what exactly are you reversing?
  1. A str is a sequence of code points
  2. [::-1] reverses code points
  3. In ASCII, code point = character
  4. In Unicode, split clusters first

For exercises and ASCII data, [::-1] is all you need. For text a user will read, split it into grapheme clusters before reversing.

General pattern

python
backwards = sequence[::-1]              # str, list or tuple
backwards = "".join(reversed(text))     # iterator -> str

def is_palindrome(text: str) -> bool:
    cleaned = "".join(c for c in text.casefold() if c.isalnum())
    return cleaned == cleaned[::-1]

Reach for [::-1] by default, and normalise the text before you compare it with its reverse.

Example: the techniques, palindromes and Unicode

This script shows four ways to reverse a string plus a palindrome check. The palindrome function uses casefold() and isalnum(), so a sentence with commas and a colon is handled correctly. The last section shows that code points are not characters; ascii() prints the invisible combining mark as \u0301 so you can see where it went.

reverse_string.py
# ===== 1. Slicing: the idiomatic way =====
text = "Python"
print(f"Original:             {text}")
print(f"Slicing [::-1]:       {text[::-1]}")

# ===== 2. reversed() + join() =====
print(f"reversed() + join():  {''.join(reversed(text))}")

# ===== 3. Loop (shows the idea, but O(n^2)) =====
result = ""
for char in text:
    result = char + result
print(f"Loop:                 {result}")


# ===== 4. Recursion (practice only: depth limit) =====
def reverse_string(s: str) -> str:
    if len(s) <= 1:
        return s
    return reverse_string(s[1:]) + s[0]


print(f"Recursion:            {reverse_string(text)}")


# ===== 5. Real world: palindrome check =====
def is_palindrome(s: str) -> bool:
    cleaned = "".join(ch for ch in s.casefold() if ch.isalnum())
    return cleaned == cleaned[::-1]


print(f"\n'radar' palindrome?  {is_palindrome('radar')}")
print(f"'Python' palindrome? {is_palindrome('Python')}")
print(f"'A man, a plan, a canal: Panama' palindrome? "
      f"{is_palindrome('A man, a plan, a canal: Panama')}")

# ===== 6. Code points are not always characters =====
word = "cafe\u0301"          # 'e' followed by a combining acute accent
print(f"\nlen(word): {len(word)}")
print(f"ascii(word[::-1]): {ascii(word[::-1])}")

Code breakdown

  1. Negative step sliceprint(f"Slicing [::-1]: {text[::-1]}")

    With start and stop omitted and a step of -1, the slice walks from the last character to the first. It returns the new string "nohtyP" and leaves text unchanged.

  2. Iterator joined backprint(f"reversed() + join(): {''.join(reversed(text))}")

    reversed() is an iterator, and ''.join() concatenates its characters with nothing in between. Note that join() is a method of the separator string.

  3. Prepending in a loop result = char + result

    Each character is placed in front of what was built so far, so the result ends up reversed. Every iteration builds a new string, which is slow for long text.

  4. Base case and recursive step return reverse_string(s[1:]) + s[0]

    It reverses everything after the first character, then appends the first character at the end. len(s) <= 1 is the base case, so an empty string also stops correctly; a base case of len(s) == 0 would be correct too, just one call deeper.

  5. Normalised palindrome cleaned = "".join(ch for ch in s.casefold() if ch.isalnum())

    Folding case and keeping only letters and digits gives "amanaplanacanalpanama". Using replace(" ", "") alone would remove only spaces, so sentences with commas would fail.

  6. Accent moved to the frontprint(f"ascii(word[::-1]): {ascii(word[::-1])}")

    word holds five code points: c, a, f, e and the combining accent. After reversing, the accent sits at the very front attached to nothing. A user sees "é" as one letter; Python sees two code points.

You should see
Original:             Python
Slicing [::-1]:       nohtyP
reversed() + join():  nohtyP
Loop:                 nohtyP
Recursion:            nohtyP

'radar' palindrome?  True
'Python' palindrome? False
'A man, a plan, a canal: Panama' palindrome? True

len(word): 5
ascii(word[::-1]): '\u0301efac'

Reversing by user-perceived characters

unicodedata.normalize("NFC", text) merges combinable pairs such as e plus an accent into a single é, which rescues some cases. It cannot merge sequences that have no precomposed form, Myanmar consonant-medial-vowel stacks, or emoji sequences.

The standard library has no grapheme-cluster splitter. Use the \X pattern of the third-party regex package, or a dedicated grapheme segmentation library, to get a list of clusters and reverse that list. Before adding such a dependency, agree with the product side on what "reversed" should even mean for this feature.

A note on memory

[::-1] builds a whole new string, so reversing a 100 MB log costs roughly another 100 MB. If you only need the last lines, skip the reversal and use something like collections.deque(file, maxlen=100).

In real projects

In real projects

Production code rarely reverses a string for its own sake, but the ideas behind it show up everywhere: checking palindromes and symmetry, flipping bit order in binary strings, showing a list newest-first with items[::-1] or reversed(items), and storing domain names reversed, like "com.example.www", so they can be searched by suffix.

For any feature that touches user text, put ASCII, accented Latin, Myanmar text, emoji and the empty string in your test data, and state in the docstring whether the function reverses code points or graphemes. In interviews, showing [::-1] first and then explaining why the loop version is O(n²) is the answer people are looking for. Interviewers often follow up by asking you to reverse in place with two indices moving towards each other, which is a list exercise, since a str cannot be modified.

Common mistakes

Common mistakes

Treating reversed() as a string

name = reversed("Sai") followed by name.upper() raises AttributeError, and printing it shows <reversed object at 0x...>. Use "".join(reversed(...)) or [::-1] when you need a string. There is no text.reverse() either; that method exists only on lists.

Comparing before normalising

"Racecar" == "Racecar"[::-1] is False because R and r differ. Code that strips only spaces fails on "Was it a car or a cat I saw?" because of the question mark. Apply casefold() and an isalnum() filter before reversing.

Testing only ASCII and trusting Unicode

Passing with English test data says nothing about combining marks, Myanmar text or emoji. If the result will be shown to users, add explicit tests for those cases.

Mini challenge

Reverse at the word level

Write three functions that take a sentence. reverse_words() reverses the word order, reverse_each_word() keeps the order but reverses every word, and palindromic_words() returns the words that are palindromes.

  • Extra leading, trailing and repeated spaces must not appear in the result
  • palindromic_words() ignores case and skips one-letter words
  • An empty string is handled without errors
word_reverse.py
def reverse_words(sentence: str) -> str:
    """'  hello   big world ' -> 'world big hello'."""
    # TODO: split into words, reverse their order, join with one space
    return ""


def reverse_each_word(sentence: str) -> str:
    """'hello big world' -> 'olleh gib dlrow' (word order kept)."""
    # TODO: reverse every word on its own
    return ""


def palindromic_words(sentence: str) -> list[str]:
    """Words longer than one letter that read the same backwards."""
    # TODO: compare a casefolded word with its reverse
    return []


line = "  Anna saw a racecar at noon   "
# TODO: print repr() of each result for line, then try ""

Expected: 'noon at racecar a saw Anna', 'annA was a racecar ta noon' and ['Anna', 'racecar', 'noon'], then '' for the empty string.

Show hint

sentence.split() with no argument already drops extra whitespace. Rebuild the sentence with " ".join(...).

Show solution
word_reverse.py
def reverse_words(sentence: str) -> str:
    """'  hello   big world ' -> 'world big hello'."""
    return " ".join(reversed(sentence.split()))


def reverse_each_word(sentence: str) -> str:
    """'hello big world' -> 'olleh gib dlrow' (word order kept)."""
    return " ".join(word[::-1] for word in sentence.split())


def palindromic_words(sentence: str) -> list[str]:
    """Words longer than one letter that read the same backwards."""
    found = []
    for word in sentence.split():
        folded = word.casefold()
        if len(folded) > 1 and folded == folded[::-1]:
            found.append(word)
    return found


line = "  Anna saw a racecar at noon   "
print(repr(reverse_words(line)))
print(repr(reverse_each_word(line)))
print(palindromic_words(line))
print(repr(reverse_words("")))

Quick quiz 1 / 3

With text = "Python", what is text[::-2]?

Quick quiz 2 / 3

What does print(reversed("abc")) print?

Quick quiz 3 / 3

On a default CPython, what happens if you reverse a 5,000-character string with the lesson's recursive reverse_string()?

What to remember

  • text[::-1] is the standard, O(n) way to reverse a string
  • reversed() returns an iterator, so pair it with "".join()
  • The loop and recursive versions are O(n²), and recursion can hit the depth limit
  • Normalise with casefold() and isalnum() before checking a palindrome
  • [::-1] reverses code points, which can break combining marks, Myanmar text and emoji

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Reverse String (Enhanced) | Thuta Learning