Sub topic 2
Reading One Character with a Zero-Based Index
What this chapter assumes
You should be able to run Python code in a REPL or a script, assign a string literal to a variable, call print() and len(), and read a simple try/except block. This chapter covers reading a single character with a non-negative integer index. Negative indexes, the details of IndexError, and slicing each get their own chapter. They appear here only when they help explain the main idea.
The working model
A Python string is an ordered sequence. Each character sits at a fixed position, and each position has a number called its index. The first character has index 0, the second has index 1, and so on. Writing s[i] asks Python for the character at index i.
s = "Python"
print(s[0])
print(s[5])
print(len(s))
print(s[len(s) - 1])This prints P, n, 6 and n. The string has six characters, so the valid indexes run from 0 to 5.
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character | P | y | t | h | o | n |
Why counting starts at zero
Think of the index as an offset: how many steps you move from the start of the string to reach the character. The first character is zero steps from the start, so its index is 0. The character at index 3 is three steps away from the first one.
This has a practical consequence for lengths. A string of length n has indexes 0 through n - 1. The last character is always at len(s) - 1, and there is never a character at index len(s). Most beginner mistakes with indexing come from forgetting this.
The result is a string, not a character type
Python has no separate character type. When you index a string, you get back a new string of length 1. This matters when the character is a digit, because it is still text.
digits = "2024"
first = digits[0]
print(first, type(first))
print(first == 2)
print(int(first) + 1)
print(len(first))
print(first[0])The output is:
2 <class 'str'>
False
3
1
2The comparison with the integer 2 is False because "2" and 2 are different types. To do arithmetic, convert with int(). Because the result is a one-character string, it can be indexed again, and first[0] is the same character.
The index is any integer expression
The value inside the brackets does not have to be a literal. It can be a variable, a calculation, or a function call, as long as it evaluates to an integer.
s = "Python"
i = 2
print(s[i])
print(s[i + 1])
print(s[len(s) // 2])
try:
s[1.5]
except TypeError as e:
print(type(e).__name__)This prints t, h, h and TypeError. The expression len(s) // 2 uses integer division, which gives 3. A float such as 1.5 is rejected with a TypeError, even if it is a whole number like 1.0. If a calculation might produce a float, use // or int() before indexing.
Every character counts, including spaces
A space, a comma, or a newline is a character with its own index. If you count positions by eye, it is easy to skip them.
t = "Hi there"
print(repr(t[2]))
print(t[3])This prints ' ' and then t. The string is H, i, a space, then t, h, e, r, e, so the space sits at index 2 and the first t at index 3. The repr() call is useful here because it shows the quotes, which makes a space or other whitespace character visible.
Using indexes in a loop
When you need to visit every character along with its position, you can loop over the valid indexes with range(len(s)).
s = "Python"
for i in range(len(s)):
print(i, s[i])range(len(s)) produces 0 through 5, which matches the valid indexes exactly. This is the correct place to use len(s) as an upper limit, because range stops before its end value.
In most cases there is a cleaner option. If you only need the characters, loop over the string directly. If you need both the index and the character, use enumerate().
s = "Python"
for ch in s:
print(ch)
for i, ch in enumerate(s):
print(i, ch)Reach for s[i] inside a loop only when the index drives something else, such as comparing s[i] with s[i + 1]. In that case, remember that the loop must stop one index early so that i + 1 stays valid.
Edge case: the empty string
An empty string has length 0, so it has no valid index at all. Even ""[0] fails. If your code reads the first character of text that might be empty, check for that case first.
def first_char(text):
if text:
return text[0]
return None
print(first_char("Python"))
print(first_char(""))This prints P and None. An empty string is falsy, so if text: is a compact way to test that at least one character exists. The next chapters cover what happens when you index outside the valid range and how to handle it.
Strings are read-only
Indexing reads a character. It does not let you change one. An assignment such as s[0] = "J" is an error, because strings cannot be modified in place. A later chapter explains this and shows how to build a changed string from the original. For now, treat s[i] as something you can read but never assign to.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Treating the first character as index 1 | You get the second character | Start counting at 0 |
| Using `s[len(s)]` for the last character | The index is one past the end | Use `s[len(s) - 1]` |
| Expecting `"2024"[0]` to be the integer 2 | It is the string `"2"` | Convert with `int()` |
| Skipping spaces when counting positions | Your index is off by the number of skipped characters | Count every character and use `repr()` to see whitespace |
| Indexing with a float such as `len(s) / 2` | `TypeError` | Use `//` or `int()` |
| Reading `text[0]` without checking for empty text | The program fails on empty input | Test `if text:` first |
Summary of the model
s[i]returns the character at offsetifrom the start, as a new one-character string.- Valid non-negative indexes run from
0tolen(s) - 1. - The index must be an integer, though it can be any expression that produces one.
- Spaces and punctuation have indexes like any other character.
- An empty string has no valid index.
- Indexing reads characters but cannot assign to them.
Exercise
Given word = "level up", what does repr(word[5]) print, and why?
Show answer
It prints ' ' (a single space). The characters are l (0), e (1), v (2), e (3), l (4), a space (5), u (6) and p (7). The space is a character with its own index, so word[5] is a one-character string containing a space, and repr() shows it with quotes.
Exercise
A string s has length 10. Which index reads its last character, and why does s[10] not work?
Show answer
The last character is at s[9], which is s[len(s) - 1]. Indexes start at 0, so a string of length 10 has valid indexes 0 through 9. Index 10 is one past the end, and there is no character there.