Online Tutorials & Training Materials | STechies.com
Register Login

TypeError: String Indices Must be Integers

19 Aug 2019 1:16 pm || 0

TypeError: String Indices Must be Integers

All the characters of a string have a unique index. This index specifies the position of each character of the string. But you have to remember that all the indexes are integers. When you specify a string or a float as the index, you will encounter an error called TypeError: String Indices Must be Integers. You have to always assign an integer value to the indices.

print(mystring['first'])

print(mystring[1.2])

Error Example

# Python3 code example

# Initializing string with name mystring
mystring = 'Hello Stechies'

print(mystring['first'])

Output:

Traceback (most recent call last):
  File "string-integers.py", line 6, in <module>
    print(mystring['first'])
TypeError: string indices must be integers json.

When we initializing a string, it starts indexing each character of the string. In the above code example, we are trying to print the value of the first index or character of a string name “mystring” by setting the first index as ‘first’

As we already know that the value of the index is always an integer, not a character this is the reason we get this error ‘string indices must be integers’.

TypeError: String Indices Must be Integers

Correct example:

# Python3 code example

# Initializing string with name mystring
mystring = 'Hello Stechies'

print('Output: ' + mystring[1])

Output:

Output: e

Error: typeerror string indices must be integers not float

This type of error occurs when we set ‘float’ value of the first index instead of an ‘integer’ while initializing a string.

Error Example

# Python3 code example

# Initializing string with name mystring
mystring = 'Hello Stechies'

print(mystring[4.2])

Output:

Traceback (most recent call last):
  File "string-integers.py", line 6, in <module>
    print(mystring[4.2])
TypeError: string indices must be integers not float

Correct example

# Python3 code example

# Initializing string with name mystring
mystring = 'Hello Stechies'

print('Output: ' + mystring[4])

Output:

Output: o

Conclusion

So if you encounter the TypeError, check the type of indices that you have already mentioned. Always make sure that the first index and the rest are integers.