Print Last Character
Access the final character of a Python string with negative indexing. Students check for empty input and distinguish index minus one from a one-based position.
1# Take string input2s = input("Enter a string: ")34# Print last character5if len(s) > 0:6 print(f"Last character: {s[-1]}")7else:8 print("String is empty")
Output
Enter a string: Hello Last character: o
In this one
- Use an index from the end
- Guard endpoint access
- Retain trailing spaces
How it works
- 1
Require a nonempty response.
- 2
Select s[-1].
- 3
Print that character or the empty-input message.
Edge cases
What happens for empty input?
What happens for empty input?
The code prints String is empty.
What about a one-character string?
What about a one-character string?
Its only character is also the last one.
What's going on
s[-1] selects the last code point without calculating len(s) - 1 explicitly. The nonempty guard must run first.
For hello, it selects o. Trailing spaces remain in the input and can therefore be the last character. A one-character string has the same first and last character; an empty response has neither and reaches the message branch.
What happens for empty input? The code prints String is empty.
What about a one-character string? Its only character is also the last one.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does index -1 mean?
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 code prints String is empty.
What about a one-character string?
Its only character is also the last one.
What does index -1 mean?
The final character.
๐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