Slice it with a step of -1.
word = "stressed" print(word[::-1])
desserts
Why [::-1] works
A slice is [start:stop:step]. Leave out start and stop and you get the whole string; a step of -1 walks through it backwards. Other steps work the same way:
letters = "abcdefgh" print(letters[::2]) # every second letter print(letters[::-2]) # every second letter, from the end print(letters[2:5]) # positions 2, 3 and 4
aceg hfdb cde
The readable alternative
reversed() returns the characters in reverse order, and "".join glues them back into a string. Longer, but someone new to Python can read it:
word = "stressed" print("".join(reversed(word)))
desserts
reversed(word) on its own is not a string; printing it shows <reversed object at 0x...>. The join is what turns it back into text.
A common use: palindromes
def is_palindrome(text): letters = [c.lower() for c in text if c.isalnum()] return letters == letters[::-1] print(is_palindrome("Never odd or even")) print(is_palindrome("Python"))
True False
Slicing works on lists too, as you can see. Removing spaces and punctuation first is what makes "Never odd or even" count.
Reversing words, not letters
sentence = "the quick brown fox" print(" ".join(sentence.split()[::-1]))
fox brown quick the
One limit worth knowing: [::-1] reverses code points, not what you see as letters. An accent stored as a separate combining mark, or an emoji built from several parts like a family or a flag, comes apart when reversed. For names and plain words it never matters; for user-generated text with emoji, it can.