Bootstrap FreeKB - Python (Scripting) - Resolve "TypeError: string indices must be integers"
Python (Scripting) - Resolve "TypeError: string indices must be integers"

Updated:   |  Python (Scripting) articles

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
var1 = "Hello World"
print(var1)

 

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, the var1 variable contains a string (Hello World). In other words, the var1 variable does not contain a key named "foo".

#!/usr/bin/python
var1 = "Hello World"
print(var1['foo'])

 

It is also noteworthy that since var1 contains a string, each indice in the string can be accessed with the index number of the indice.

#!/usr/bin/python
var1 = "Hello World"
print(var1[0])
print(var1[1])
print(var1[2])
print(var1[3])
print(var1[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 Buy Me A Coffee



Comments


Add a Comment


Please enter af6ad7 in the box below so that we can be sure you are a human.