2.7 String operations
In this section, we work with this line fragment from Shakespeare’s Hamlet:
quote = "perchance to dream"
quote
'perchance to dream'
Since we’ll need it several times, let’s save the number of characters in the str
.
quote_length = len(quote)
quote_length
18
2.7.1 Accessing characters
The first character is at index 0
, and the last is at index
quote_length - 1
.
quote[0]
'p'
quote[quote_length - 1]
'm'
Python raises an error if you try to access a character beyond this final valid index.
quote[quote_length]
IndexError: string index out of range
Exercise 2.10
What happens if you try to access a character at index 0
in
an empty string?
Python does something interesting if you use a negative integer as an index.
quote[-1]
...