Indexing
A string is a sequence of characters, and every character has a position, called its index. Square brackets pull one character out by its index.
Counting from the front
Positions start at 0, not 1:
word = "python"print(word[0])print(word[3])word[0] is the first letter, p. word[3] is the fourth letter, h.
Counting from the back
A negative index counts from the end, starting at -1:
name = "Sanjin"print(name[-1])print(name[-2])name[-1] is the last letter, n. name[-2] is the one before it, i.
The last position
len() counts the characters. Positions start at 0, so the last position is
len(word) - 1. The index can be a variable:
word = "cat"last = len(word) - 1print(len(word))print(last)print(word[last])"cat" has 3 characters at positions 0, 1 and 2, so word[2] is t.
Stay inside the string
An index past the last position is an error. "cat" has no position 3:
word = "cat"
print(word[3]) # IndexError: string index out of range
An empty string "" has no characters, so even word[0] raises IndexError.
See also: Lists use the same positions, String methods.
Your turn
Print the first character, then the last character, on separate lines.
k o
word = "kangaroo"# Add two print statements.Advanced reading
- String slicing — take part of a string with
[start:stop], skip with a step, and reverse it. - List slicing and joining — the same slices on lists, plus
+and*.