Print First Character
Print a string's first character safely with indexing. Beginners guard empty input before using index zero and see why leading spaces are real characters.
1# Take string input2s = input("Enter a string: ")34# Print first character5if len(s) > 0:6 print(f"First character: {s[0]}")7else:8 print("String is empty")
Output
Enter a string: Hello First character: H
In this one
- Index from zero
- Guard empty strings
- Retain leading spaces
How it works
- 1
Check the entered string has positive length.
- 2
Read s[0] only in that branch.
- 3
Otherwise print String is empty.
Edge cases
What if the response is empty?
What if the response is empty?
String is empty is printed.
What if the response starts with a space?
What if the response starts with a space?
That space is the selected character.
What's going on
The length check ensures s[0] exists. Python indexes from zero, so that position contains the first code point.
For hello, the displayed character is h. A leading space is also a first character and is not automatically trimmed. If the response is empty, the else message prints instead of an invalid indexing operation.
What if the response is empty? String is empty is printed.
What if the response starts with a space? That space is the selected character.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which index selects the first character?
Pick an answer to check it.
Question 2
What if the response is empty?
Pick an answer to check it.
Questions people ask
What if the response is empty?
String is empty is printed.
What if the response starts with a space?
That space is the selected character.
Which index selects the first character?
0.
๐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