Remove Last Character
Drop the character with a slice. Students trace an excluded negative endpoint and distinguish removing one position from stripping repeated trailing characters.
1# Take string input2s = input("Enter a string: ")34# Remove last character5if len(s) > 0:6 result = s[:-1]7 print(f"After removal: {result}")8else:9 print("String is empty")
Output
Enter a string: Hello After removal: Hell
In this one
- Exclude the final position
- Read a negative slice endpoint
- Remove only one character
How it works
- 1
Check that a final character exists.
- 2
Create result with s[:-1].
- 3
Print the shortened string or empty-input feedback.
Edge cases
What if s has one character?
What if s has one character?
The result is empty.
Does this remove every trailing space?
Does this remove every trailing space?
No. It removes only the last character.
What's going on
s[:-1] takes every position before the final one. The endpoint is excluded, so exactly one character is omitted for nonempty input.
For cat, the result is ca. A trailing space is still a character and is removed before any earlier letter. This is not rstrip, which can remove a run of trailing characters. The empty branch reports that no final character exists.
What if s has one character? The result is empty.
Does this remove every trailing space? No. It removes only the last character.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does -1 identify in the slice?
Pick an answer to check it.
Question 2
What if s has one character?
Pick an answer to check it.
Questions people ask
What if s has one character?
The result is empty.
Does this remove every trailing space?
No. It removes only the last character.
What does -1 identify in the slice?
The excluded final position.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum