Let's say you have the following Python script. Running this script should produce no errors and Hello World should be printed.
#!/usr/bin/python
my_variable = "Hello World"
print(my_variable)
On the other hand, let's say you have the following. Running this script should return TypeError: string indices must be integers, not str. This occurs because, in this example, my_variable contains a string (Hello World). In other words, my_variable does not contain a key named "foo".
#!/usr/bin/python
my_variable = "Hello World"
print(my_variable['foo'])
It is also noteworthy that since my_variable contains a string, each indice in the string can be accessed with the index number of the indice.
#!/usr/bin/python
my_variable = "Hello World"
print(my_variable[0])
print(my_variable[1])
print(my_variable[2])
print(my_variable[3])
print(my_variable[4])
Should print the following.
H
e
l
l
o
This error is much more common when working with a dictionary (key:value pairs). Let's say you have the following Python script. Running this script should return TypeError: string indices must be integers, not str because the key must be used as the reference inside of the brackets.
#!/usr/bin/python3
dictionary = {
'foo':'Hello',
'bar':'World'
}
print(dictionary['foo']) # <- correct
print(dictionary['bar']) # <- correct
for key in dictionary:
print(dictionary[key]) # <- correct
print(key['foo']) # <- incorrect
Did you find this article helpful?
If so, consider buying me a coffee over at 