Python strings are immutable, and to reverse them, you need to always return a new string without modifying the original.
To efficiently reverse a string in Python, use slicing ([::-1]). The colon (:) means we need to select the whole string (no explicit start/stop), and -1 suggests moving backwards through the string (from right to left). It is an idiomatic and concise approach.
In simple terms, an interpreter starts at the end and steps back one character at a time until it reaches the beginning.
original_str = "dividend" reversed_str = original_str[::-1] print(reversed_str) # Output: dnedivid
The output string “dnedivid” is an exact reversal of the input string “dividend”.
Empty string
If you try to reverse an empty string, the output string will be empty without any errors. So, you don’t need to worry about an empty case.
empty_str = "" reversed_str = empty_str[::-1] print(reversed_str) # Output: "" (an empty string)
Single character
If the input string contains only a single character, the reversal would be the exact string because one character’s reversal is itself.
single_str = "k" reversed_str = single_str[::-1] print(reversed_str) # Output: k
All identical characters
The reversal of an all-identical-character string is the exact string as input.
identical_str = "kkk" reversed_str = identical_str[::-1] print(reversed_str) # Output: kkk
Unicode/Multibyte characters
Even if the string contains Unicode/multibyte characters, Python 3 handles UTF-8 natively, ensuring no byte-level breakage.
unicode_str = "café" reversed_str = unicode_str[::-1] print(reversed_str) # Output: éfac
Mixed case and spaces
Slicing preserves casing/whitespace while reversing the string.
spaced_str = "howdy mate" reversed_str = spaced_str[::-1] print(reversed_str) # Output: etam ydwoh
Other approaches
Using reversed() Iterator with join()
The reversed() function returns an iterator that yields characters in reverse, and using the .join() method, you can join the characters, making it a complete reversal string.
normal_str = "Dividend" reversed_str = ''.join(reversed(normal_str)) print(reversed_str) # Output: dnediviD
Using functools.reduce()
It is a functional one-liner that you can use to reverse a string with the help of the functools package.
from functools import reduce normal_str = "Dividend" reversed_str = reduce(lambda x, y: y + x, normal_str) print(reversed_str) # Output: dinevdiD
That’s all!






