(Help) TypeError: ‘str’ object cannot be interpreted as an integer

It seems from your error than the ‘index’ variable is a string, not an int. You could convert it using int().

index = int(index)
for i in range(string[index:]):   

Now, string[index:] will also be an string. So you would need to convert that too:

>>> string = "5"
>>> range(string)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got str.
>>> range(int(string))
[0, 1, 2, 3, 4]
>>>

That’s assuming that string[index:] only contains a number. If that’s not always the case, you can do something like:

# 'index' contains only numbers
index = int(index)
number = string[index:]
if number.isdigit():
    number = int(number)
    for i in range(number):   

From the Wikipedia article on Python:

Python uses duck typing and has typed objects but untyped variable names. Type constraints are not checked at compile time; rather, operations on an object may fail, signifying that the given object is not of a suitable type. Despite being dynamically typed, Python is strongly typed, forbidding operations that are not well-defined (for example, adding a number to a string) rather than silently attempting to make sense of them.

In this case, you try to pass a string to range(). This function waits for a number (a positive integer, as it is). That’s why you need to convert your string to int. You could actually do a bit more of checking, depending on your needs. Python cares for types.

HTH,

Leave a Comment