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

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.

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

    Require a nonempty response.

  2. 2

    Select s[-1].

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