
You already know about this error from Lists. If you encounter an IndexError with a string index, it works exactly the same way for Strings (text).
A string is just a sequence of characters.
text = "Python"
# P = index 0
# y = index 1
# ...
# n = index 5The length is 6, but the last index is 5.
The Cause
Trying to access a character that doesn’t exist.
text = "Hi"
print(text[2])
# CRASH! Index 2 doesn't exist (only 0 'H' and 1 'i' exist)Common Scenario: Empty Strings
This often happens when looping through data where some entries might be blank.
def get_first_letter(word):
return word[0] # DANGER!
print(get_first_letter(""))
# CRASH! An empty string has NO index 0.The Fix
Always check if the string is empty before trying to access a specific index.
def get_first_letter(word):
if len(word) > 0: # Or just 'if word:'
return word[0]
else:
return None




