Reverse a String in Python
Reverse a String in Python
One of the most common Python interview questions is reversing a string. Python makes this elegant with slicing.
The Pythonic Way
def reverse_string(s):
return s[::-1]
# Example
print(reverse_string("hello")) # Output: "olleh"
How It Works
The slicing syntax s[::-1] means: start from the end, go to the beginning, step by -1 (backwards). It is the most concise and readable solution.
Alternative: Using a Loop
def reverse_string_loop(s):
result = ""
for char in s:
result = char + result
return result
print(reverse_string_loop("hello")) # Output: "olleh"
Alternative: Using reversed()
def reverse_string_builtin(s):
return "".join(reversed(s))
print(reverse_string_builtin("hello")) # Output: "olleh"
Key Takeaway
Use s[::-1] for simplicity and performance. It is the standard Pythonic approach widely accepted in interviews and production code.
(Visited 1 times, 1 visits today)