Reverse a String Program in Python
Problem statement
Turn a string such as "python" into "nohtyp" — build the characters in the opposite order without changing the original string.Approach 1: simple loop
Walk the string from the last character to the first and collect them one by one. len(s) - 1 is the last position, and the loop counts down to 0.
s = "python"
reversed_text = ""
for i in range(len(s) - 1, -1, -1):
reversed_text = reversed_text + s[i]
print(reversed_text)
# Output: nohtypEach iteration adds one character to the front-runner string. Slow for huge inputs, but it shows exactly what "reversing" means.
Approach 2: reusable function
Put the loop in a function and return the result. A function makes the operation reusable and keeps the original string untouched — the caller stores the returned value.
def reverse_string(text):
result = ""
for ch in text:
result = ch + result # prepend: new char goes in FRONT
return result
print(reverse_string("python")) # nohtyp
print(reverse_string("a")) # a
print(reverse_string("")) # (empty string)This version walks forwards but prepends each character, which reverses just as well — and handles the empty string with no extra code.
Approach 3: Pythonic alternative
Python's slice notation has a built-in step argument, and a step of -1 walks the whole string backwards in one expression — the idiomatic answer.
s = "python"
print(s[::-1]) # nohtyp
print("".join(reversed(s))) # nohtyp — the explicit cousin[::-1] reads "from start to end, stepping backwards". The reversed() + join() form spells the same idea out longhand and is easier to adapt when you need every second character or a partial reverse.
Dry run
Trace "abc" through the prepend version. Start: result = "". After 'a': "a". After 'b': "ba" — the new character went in front. After 'c': "cba". Each step is just "one character, then everything collected so far". For the slice version, think of the string as a row of positions walked right-to-left: positions 5, 4, 3, 2, 1, 0 of "python" spell nohtyp.
Common errors
- Calling
s.reverse()— strings have no reverse method; lists do. Use slicing instead. - Trying to swap characters in place — strings are immutable, assignment into
s[i]raises a TypeError. - An off-by-one in the countdown loop:
range(len(s), 0, -1)misses the first character. - Confusing
reversed(s)(an iterator) with a string — it must be joined before printing. - Appending instead of prepending in the loop version, which rebuilds the same string.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: