Online Tutorials & Training Materials | STechies.com
Register Login

TypeError: String Indices Must be Integers

|| 0

TypeError: String Indices Must be Integers
Stechies

This type of error occurs usually when we set the first index value of string as character or non integer. 

print(mystring['first'])

print(mystring[1.2])

In this tutorial we have explained error such as following with best solution. 

Error: typeerror: string indices must be integers json

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, its start indexing each character of the string. In the above code example we are trying to print the value of first index or character of a string name “mystring” by setting the first index as ‘first’

As we already know that the value of index is always an integer not a character this is the reason we get this error ‘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 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