我已经输入了这个代码,但我看不出有什么不妥的地方。“无法将‘诠释’对象隐含STR”的错误还是什么?
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
它不断给我“无法将‘诠释’对象隐含STR”即使我转换的整数转换成字符串
说明了这个小白吗?
我已经输入了这个代码,但我看不出有什么不妥的地方。“无法将‘诠释’对象隐含STR”的错误还是什么?
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
它不断给我“无法将‘诠释’对象隐含STR”即使我转换的整数转换成字符串
说明了这个小白吗?
试试这个:
>>> 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_input
是input对于相同的功能...)
你只需把你的print
的if
块内。
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已经提到了新的字符串格式化方法。
哦,顺便说一下,它是直接从一本书复制的(不用担心,我研究过它:P) – omgflyingbanana 2013-02-21 22:16:58
[TypeError:无法将int对象隐式转换为str](http ://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly) – bernie 2013-02-21 22:21:25
把'print'里面的'if'阻止 – Volatility 2013-02-21 22:22:46