This guide explains String Indexing: Access Characters by Position through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
String indexes select code points by position, starting at 0. Negative indexes count from the right. Direct indexing raises IndexError when the position does not exist.
When You Would Use This
Read the prefix and suffix of a short identifier.
Step-by-Step Example
serial_code = "AB-927"
print(serial_code[0])
print(serial_code[1])
print(serial_code[-1])
How the Example Works
The first two characters are A and B, and the last character is 7. The hyphen also occupies an index position.
Example Output
A
B
7
Try It Yourself
Print the third character of "Notebook", then try the last index by using len() - 1.
Common Beginner Mistakes
- Expecting
serial_code[1]to return the first character. - Indexing into an empty string without checking its length.
- Treating a displayed combined character as exactly one stored code point.
Key Takeaways
- String indexes select code points by position, starting at 0.
- The first two characters are A and B, and the last character is 7.
- Avoid this mistake: Expecting
serial_code[1]to return the first character.