Working with Text · practice
Find Characters by Position
Because a
word = "garden"
first_character = word[0]
print(first_character)
The square brackets ask for a g.
Python starts counting at zero
The characters in "garden" have these indexes:
| Character | g | a | r | d | e | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
The first character is at index 0, not index 1. This is called zero-based indexing.
print(word[0])
print(word[1])
print(word[5])
This prints g, a, and n.
The index is an integer. word["1"] does not work because the string "1" is not an index number.
Count backward with negative indexes
Python also lets you count from the end:
print(word[-1])
print(word[-2])
Index -1 means the last character. Index -2 means the character before it. The output is n and e.
Negative indexing is especially useful when you do not know the string’s length in advance.
An index must exist
"garden" has six characters, with indexes 0 through 5. Asking for word[6] reports:
IndexError: string index out of range
Python understood the indexing operation, but that position does not exist.
An empty string has no first or last character. That is why the chapter project will explicitly request a non-empty phrase.
What will this program print?
word = "code"
print(word[1])Find the ends of a word
Replace the two empty strings with indexed characters from language:
first_charactershould contain the first character;last_charactershould contain the last character.
Use index 0 for the first character and a negative index for the last. The output must be:
First: P
Last: n
Task
Use 0 to language to first_character. Use index -1 to assign its last character to last_character.
Produce:
First: P
Last: n