【问题标题】:Why is it returning cannot convert to str implicitly? [duplicate]为什么它返回不能隐式转换为 str ? [复制]
【发布时间】:2016-03-17 18:03:36
【问题描述】:

这是一个随机数学问题,会返回一个我没想到的错误。请帮忙! 错误是: print('你的分数是:'+int(score)) TypeError: 无法将“int”对象隐式转换为 str

import random


count=0


while count<10:
    numb1=random.randint(1,12)
    numb2=random.randint(1,12)
    ops=[' add ',' times ',' takeaway ']
    ops2=random.choice(ops)
    question=str(numb1)+''.join(ops2)+str(numb2)
    print(question)
    ans=int(input('Answer: '))
    count=count+1
score=0
if ans== numb1+numb2 or numb1-numb2 or numb1*numb2:
    score=score+1

print('Your score was: '+score)

【问题讨论】:

  • 可能是因为 Python 不会将整数隐式转换为字符串?
  • 你不能把 str 和它结合起来。 print('你的分数是:'+str(score))
  • print('Your score was: {}'.format(score))
  • 谢谢!现在我已经输入了 str(score))

标签: python string int


【解决方案1】:

此行不正确。不能添加intstr

print('Your score was: '+score)

使用以下方法之一:

print('Your score was:', score)
print('Your score was: '+str(score))
print('Your score was: %d'%(score))
print('Your score was: {}'.format(score))

【讨论】:

    【解决方案2】:

    在最后一行你需要将整数转换为字符串

    print('Your score was: ' + str(score))
    

    您也可以使用格式字符串:

    print('Your score was: %u' % score)
    

    这是因为您不能将整数直接连接到字符串,例如
    "I have " + 7 + " kittens" - 为此,您必须首先将整数(在本例中为 7)转换为字符串。您可以使用 Python 内置的 str() 函数来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多