Reverse Text with Slicing
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement reverse_text(value). Return the characters in reverse order without calling reversed().
Starter code
def reverse_text(value: str) -> str:
passTest cases
sample
{
"args": [
"python"
]
}Expected: "nohtyp"
Wizard outline
- Step 1: Preserve a one-character slice
Return the only character through slicing instead of indexing. A slice remains safe for an empty boundary while direct indexing would raise an exception.
- Step 2: Walk the entire string backward
Reverse every character with a negative slice step. An omitted start and stop with step -1 traverses the complete sequence in reverse order and also handles empty input.
Footguns and prerequisites
- Strings are immutable; return the new string instead of printing it.
- strings
- functions
Reviewed references
Recommended approach and implementation
Use a full slice whose step is -1.
Why it works: The slice visits every character exactly once from the final index to the first.
def reverse_text(value: str) -> str:
return value[::-1]