2016-11-06 44 views
-2
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 
    for i in range(string[index:]): 
TypeError: 'str' object cannot be interpreted as an integer 

我想用價值指數是指,但我怎麼做呢?(幫助)類型錯誤:「海峽」對象不能被解釋爲一個整數

+0

您認爲問題可能是什麼?你試過什麼了?你在搜索什麼? http://stackoverflow.com/help/how-to-ask – RJHunter

+0

請發佈您的代碼 –

回答

1

從你的錯誤看來,'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,

+0

index實際上是我函數中的一個參數,它指的是一個int,它指向string的索引值。我想用參數中的值作爲索引,我該怎麼做? def get_odd_palindrome_at(string,index): '''(str,int) - > str 返回以指定索引爲中心的字符串中最長的奇數長迴文。 –

+0

從你引用的異常(對於範圍內的字符串[string [index:]): TypeError:'str'對象不能被解釋爲一個整數),在我看來,'index'實際上包含一個字符串,而不是一個int 。你應該檢查你是否傳遞了一個整數給你的函數。請注意,一個字符串可以包含Python中的數字(以及大多數語言),var =「3」會創建一個字符串...不是整數。對不起,如果這聽起來很明顯,但有時會忘記。 –

+0

或者更短的答案,你函數中的第一行可以轉換你的索引:index = int(index)。但是檢查發送給函數的數據類型要好得多。如果你的函數需要一個字符串和一個int,那麼你應該發送一個字符串和一個int;)。 –

相關問題