從你的錯誤看來,'index'變量是一個字符串,而不是一個int。你可以使用int()來轉換它。
index = int(index)
for i in range(string[index:]):
現在,string [index:]也是一個字符串。所以你也需要轉換:
>>> 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]
>>>
這是假設string [index:]只包含一個數字。如果是這樣的情況並非總是如此,你可以這樣做:
# 'index' contains only numbers
index = int(index)
number = string[index:]
if number.isdigit():
number = int(number)
for i in range(number):
從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.
在這種情況下,你試圖傳遞一個字符串到範圍()。該函數等待一個數字(正整數,因爲它)。這就是爲什麼你需要將你的字符串轉換爲int。根據您的需求,您實際上可以做更多的檢查。 Python關心類型。
HTH,
您認爲問題可能是什麼?你試過什麼了?你在搜索什麼? http://stackoverflow.com/help/how-to-ask – RJHunter
請發佈您的代碼 –