Character Access and Indexing
What you'll learn: How to access individual letters in a string using bracket notation and zero-based indexing.
The Core Idea
Just like arrays hold multiple elements that you can access by position, strings hold multiple characters that you can access the same way. Since you already know that strings are arrays of characters (from the previous lesson), accessing individual characters works exactly like accessing array elements—using square brackets and an index number.
The key thing to remember: zero-based indexing. The first character is at position 0, the second at position 1, and so on.
How It Works
Think of a string like a row of mailboxes, each containing one letter. To get mail from a specific box, you need its position number. But programmers start counting from 0, not 1.
For the string "HELLO":
- Index 0 →
'H' - Index 1 →
'E' - Index 2 →
'L' - Index 3 →
'L' - Index 4 →
'O'
You use bracket notation just like with arrays:
word = "HELLO"
first_char = word[0] # 'H'
third_char = word[2] # 'L'
last_char = word[4] # 'O'
The length of the string is 5, but the valid indices are 0 through 4. Trying to access word[5] would be out of bounds—just like with arrays.
Why Zero-Based?
Zero-based indexing comes from how computer memory works. The index represents the offset from the start of the string. Zero means "no offset"—you're at the beginning.
Key Takeaway: Individual characters in a string are accessed using bracket notation with zero-based indices, exactly like array elements—the first character is at index 0, and the last is at index (length - 1).