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

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.

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

    Check that a final character exists.

  2. 2

    Create result with s[:-1].

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