python - (Help) TypeError: 'str' object cannot be interpreted as an integer -
traceback (most recent call last): file "<pyshell#0>", line 1, in <module> get_odd_palindrome_at('racecar', 3) file "c:\users\musar\documents\university\courses\python\assignment 2\palindromes.py", line 48, in get_odd_palindrome_at in range(string[index:]): typeerror: 'str' object cannot interpreted integer
i want use value index refers how do that?
it seems error 'index' variable string, not int. convert using int().
index = int(index) in range(string[index:]):
now, string[index:] string. need convert 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 string[index:] contains number. if that's not case, can like:
# 'index' contains numbers index = int(index) number = string[index:] if number.isdigit(): number = int(number) in range(number):
from the wikipedia article on python:
python uses duck typing , has typed objects untyped variable names. type constraints not checked @ compile time; rather, operations on object may fail, signifying given object not of suitable type. despite being dynamically typed, python typed, forbidding operations not well-defined (for example, adding number string) rather silently attempting make sense of them.
in case, try pass string range(). function waits number (a positive integer, is). that's why need convert string int. bit more of checking, depending on needs. python cares types.
hth,
Comments
Post a Comment