String Indexing
Overview
In Python, strings are ordered sequences of characters. You can access individual characters by their numerical position (index) using square brackets []. Python uses zero-based indexing (the first character is 0). Uniquely, Python also supports negative indexing, allowing you to access elements from the end of the string without needing to calculate the string's total length (e.g., -1 is the last character).
Syntax
word = "Python"
# Positive Indexing (Starts at 0, from left to right)
print(word[0]) # 'P'
print(word[3]) # 'h'
# Negative Indexing (Starts at -1, from right to left)
print(word[-1]) # 'n' (Last character)
print(word[-2]) # 'o' (Second to last character)Common Pitfalls
- IndexError: Attempting to access an index that doesn't exist (e.g.,
word[10]for a 6-letter string) crashes the program. - TypeError: Strings in Python are strictly IMMUTABLE. You cannot do
word[0] = 'J'to change 'Python' to 'Jython'. You must create a new string.
Interview Questions
Immutability guarantees that strings are thread-safe and hashable, allowing them to be used as keys in dictionaries. It also allows Python to optimize memory by reusing string objects across the program.
Real-World Example
Quickly determining file types or handling formatting by inspecting specific edge characters.
raw_data = "[System Log]"
# Verify it's a bracketed tag by checking first and last characters
if raw_data[0] == "[" and raw_data[-1] == "]":
print("Tag format verified.")
else:
print("Invalid format.")Check Your Knowledge
Test your understanding of String Indexing with these quick questions.