【问题标题】:"Can't convert 'int' object to str implicitly" bug or what?“无法将'int'对象隐式转换为str”错误或什么?
【发布时间】:2013-02-21 22:16:22
【问题描述】:

我已经输入了这段代码,但我看不出它有什么问题。

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

即使我将整数转换为字符串,它仍然给我“无法将 'int' 对象隐式转换为 str”

请帮帮这个菜鸟?

【问题讨论】:

  • 哦,对了,是直接从一本书上抄来的(放心,我研究过:P)
  • print 放在if 块内
  • 波动性,你应该把它作为答案发布
  • 您可以将其缩短为if guess != number print('Nope. The number I was thinking of was ' + str(number))

标签: python python-3.x


【解决方案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,您不需要进行显式类型转换来打印它,因为您没有连接两个字符串。不过,您需要确保在 if 语句中将字符串与字符串或 int 与 int 进行比较。

(如果您使用的是 Python 3,raw_inputinput 用于相同的功能...)

【讨论】:

    【解决方案2】:

    您只需将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 提到了较新的字符串格式化方法。

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 2015-04-12
      • 2017-03-27
      • 1970-01-01
      • 2012-11-19
      • 2017-08-24
      • 1970-01-01
      • 2013-09-27
      相关资源
      最近更新 更多