0%

Working with Text · practice

Find Characters by Position

Because a is ordered, Python can retrieve a character from a particular position.

word = "garden"
first_character = word[0]
print(first_character)

The square brackets ask for a at an . The output is g.

Python starts counting at zero

The characters in "garden" have these indexes:

Charactergarden
Index012345

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_character should contain the first character;

  • last_character should 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 the first character of language to first_character. Use index -1 to assign its last character to last_character.

Produce:

First: P
Last: n