Computer Science · Ch 8 — Strings
Accessing Characters in a String
Accessing Characters in a String
Every character inside a string occupies a numbered position, and the technique of reaching a character by its position number is called indexing. The index is written inside square brackets [ ] immediately after the string (or the variable holding it), and it tells Python exactly which character to fetch.
One fact worth fixing in mind first: Python has no separate character data type. A single character is simply a string whose length is one — so indexing a string gives you back another (one-character) string.
Positive indexing — counting from the left
Counting from the left, the first character has index 0 and the last character has index n-1, where n is the length of the string. Asking for any index outside this range raises an IndexError.
>>> s = 'Hello World!' # 12 characters, indices 0 to 11
>>> s[0] # first character
'H'
>>> s[6] # seventh character (index 6)
'W'
>>> s[11] # last character (index 11 = 12-1)
'!'
>>> s[15] # beyond index 11 -> error
IndexError: string index out of range
The index must be an integer
The index need not be a bare number — it can be any expression, built from variables and operators, provided the expression evaluates to an integer. A fractional index is rejected with a TypeError:
>>> s[2 + 4] # expression evaluates to 6 -> the 7th character
'W'
>>> s[1.5] # not an integer -> error
TypeError: string indices must be integers
Negative indexing — counting from the right
Python also permits negative index values, used when it is more natural to count characters from right to left. Counting from the right-hand side, the rightmost character has index -1, the next one -2, and so on, until the leftmost character has index -n (n being the string's length).
>>> s[-1] # first character from the right
'!'
>>> s[-12] # twelfth character from the right = leftmost
'H'
For the string 'Hello World!' the two numbering systems line up like this:
| Character | H | e | l | l | o | (space) | W | o | r | l | d | ! |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| Negative index | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
So every character can be named in two equivalent ways — s[6] and s[-6] both give 'W'.
Finding the length: the len() function
Python's inbuilt function len() returns the length of the string passed to it — the total count of characters, spaces included. For 'Hello World!' the length is 12.
>>> len(s)
12 …
| Positive Indices | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| String | H | e | l | l | o | W | o | r | l | d | ! |