TypeError: tuple indices must be integers or slices, not str

Are you getting the error “typeerror: tuple indices must be integers or slices, not str“? Yes, you have come to the right place. In this tutorial, I will show you how to solve this error.

The error “typeerror tuple indices must be integers or slices not str” occurs when we try to access a tuple at a specific index using a string instead of an integer.

[Fixed]: AttributeError: module ‘time’ has no attribute ‘clock’

[Fixed]: TypeError: tuple indices must be integers or slices, not str

You can convert string to int using ‘int()‘ to eliminate this error “TypeError: tuple indices must be integers or slices, not str“.

Here is the python code, showing how this error occurs:

py_tuple = ('EHT', 'ISH', 'AM')

py_str = '1'

# TypeError: tuple indices must be integers or slices, not str
final_value = py_tuple[py_str]

In the above python, we got this error because we are using sting as a tuple index instead of an integer.

[Solution]: Fix the error using the “int()” to convert the string to int

You can use the ‘int()‘ to convert the string to an integer to eliminate this error. Here is the python code to get rid of this error:

py_tuple = ('EHT', 'ISH', 'AM')

py_str = '1'

final_value = py_tuple[int(py_str)] 

print(final_value)  #OUTPUT: ISH

If you want to declare a dictionary, make sure to use curly braces (not parenthesis).

my_dict = {}

my_dict['name'] = 'Ali'
my_dict['age'] = 18

print(my_dict)  #OUTPUT: {'name': 'Ali', 'age': 18}

Conclusion on TypeError: tuple indices must be integers or slices, not str

Programmers, we discussed how we can solve this error “TypeError: tuple indices must be integers or slices, not str“. If you are still facing the error please let us know in the comments section. You can convert string to int using ‘int()’ to eliminate this error.

Leave a Reply