Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 5 - Category 2: Character OperationsExample 1 of 10
print-first-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Print first character
5if 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. 1

    Check the entered string has positive length.

  2. 2

    Read s[0] only in that branch.

  3. 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.