2013-02-21 35 views
0

我已經輸入了這個代碼,但我看不出有什麼不妥的地方。「無法將‘詮釋’對象隱含STR」的錯誤還是什麼?

if guess != number: 
    number = str(number) 
print('Nope. The number I was thinking of was ' + number) 

它不斷給我「無法將‘詮釋’對象隱含STR」即使我轉換的整數轉換成字符串

說明了這個小白嗎?

+0

哦,順便說一下,它是直接從一本書複製的(不用擔心,我研究過它:P) – omgflyingbanana 2013-02-21 22:16:58

+1

[TypeError:無法將int對象隱式轉換爲str](http ://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly) – bernie 2013-02-21 22:21:25

+4

把'print'裏面的'if'阻止 – Volatility 2013-02-21 22:22:46

回答

1

試試這個:

>>> number='5' 
>>> if raw_input('enter number:')!=number: 
... print('Nope. The number I was thinking of was {}'.format(number)) 

或者:

>>> number=5 
>>> if int(raw_input('enter number:'))!=number: 
... print('Nope. The number I was thinking of was {}'.format(number)) 

隨着format method你不會需要做顯式類型轉換將其打印出來,因爲你沒有連接兩個字符串。你需要確保你是一個字符串,字符串或int if語句雖然比較爲int。

(如果你使用Python 3,raw_inputinput對於相同的功能...)

0

你只需把你的printif塊內。

if guess != number: 
    number = str(number) 
    print('Nope. The number I was thinking of was ' + number) 

在你的原代碼,它打印即使你猜對了,這意味着該if塊沒有執行等number仍然是一個整數。

你也可以使用字符串格式化,以避免對number轉換成字符串。

print('Nope. The number I was thinking of was %d' % number) 

drewk已經提到了新的字符串格式化方法。

相關問題