Reverse String Recursively
Reverse text with recursive Python slicing. Students combine a reversed suffix with its first character and trace empty and single-character stopping cases.
1def reverse_string(s):2 # Base case3 if len(s) <= 1:4 return s56 # Recursive case7 return reverse_string(s[1:]) + s[0]89# Test10text = input("Enter a string: ")11result = reverse_string(text)12print(f"Reversed: {result}")
Output
Enter a string: Hello Reversed: olleH
In this one
- Reverse a suffix
- Concatenate during return
- Stop at short strings
How it works
- 1
Return s when its length is at most one.
- 2
Reverse the suffix s[1:] recursively.
- 3
Append the saved first character after that result.
Edge cases
What happens for empty input?
What happens for empty input?
The empty string returns unchanged.
Are spaces reversed too?
Are spaces reversed too?
Yes. Every character position participates.
What's going on
reverse_string works on s[1:] first, then appends s[0] to the returned result. That moves the original first character to the end.
A string of length zero or one returns unchanged. For cat, pending concatenations produce t, then ta, then tac. Slices and strings are newly created values, and recursive calls use stack space; this is not an in-place reversal.
What happens for empty input? The empty string returns unchanged.
Are spaces reversed too? Yes. Every character position participates.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why append s[0] after the call?
Pick an answer to check it.
Question 2
What happens for empty input?
Pick an answer to check it.
Questions people ask
What happens for empty input?
The empty string returns unchanged.
Are spaces reversed too?
Yes. Every character position participates.
Why append s[0] after the call?
The first character belongs at the reversed end.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum