In this lesson, you will learn how to reach inside a string to pick out an individual character using its specific position, known as an index.
Understanding Zero-Based Indexing
Think of a string like a row of mailboxes, where each letter of your word is stored in its own individual box. To get a specific letter, you need to provide its "address." In Python, we use square brackets [] to specify the address, or index, of the character we want.
Crucially, Python uses zero-based indexing. This means the counting doesn't start at 1; it starts at 0. The first character is at index 0, the second is at index 1, the third is at index 2, and so on.
Putting It Into Practice
Imagine you have the string "Python". Here is how the computer sees the positions:
| P | y | t | h | o | n |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
If you want to access the first letter 'P', you use index 0. If you want the fourth letter 'h', you use index 3.
language = "Python"
# Retrieve specific characters
first_letter = language[0]
fourth_letter = language[3]
print(first_letter) # Output: P
print(fourth_letter) # Output: h
Why Does This Matter?
Accessing individual characters allows you to inspect or process textual data piece by piece. For example, if you wanted to check if a word starts with a specific letter, or if you wanted to loop through a string to count how many times a character appears, indexing is the tool that makes that possible.
Remember: because strings are immutable (as we discussed in lesson 9), you can use these indices to read or retrieve a character, but you cannot use indexing to change a character inside an existing string.
Key Takeaway: Python uses zero-based indexing to identify character positions, meaning the first character of any string is always found at index 0.