← All lessons

Indexes: s[0]

Sign in · Sign up

Lesson 4.0

Every character of a string has a number — an index — and counting starts at zero:

word = "Python"
print(word[0])   # P
print(word[1])   # y
print(word[-1])  # n — the last character

Square brackets are not a call but "take the character with this number". -1 is a short way to take the last character: word[len(word) - 1] does the same thing.

A number beyond the string is an error: "Python" has no index 10.

The word is set by the check. Print its first and last character, each on a new line.

Hint

The index goes in square brackets right after the name: word[0].

The first item is index 0, the last one is -1 or len(word) - 1. Bounds: for a word of length n, the index n no longer exists.