在我的Python代码中(由于rep< 10,我无法将其显示为图像),我正在尝试制作一个询问用户姓名的程序,然后猜测他们的年龄从1到30。由于某种原因,该行开始" AgeQ =" (L16)不起作用,因为它无法转换' int'反对str含义'。下面是代码和错误日志等中的错误,非常感谢帮助。
AgeQ = 'Are you ' + Age[x] + 'years old? (Y/N)'
Traceback (most recent call last):
File "\\rhs-vmw-p-fs01\students\2010\R07972\Python\test2.py", line 16, in <module>
AgeQ = 'Are you ' + Age[x] + 'years old? (Y/N)'
TypeError: Can't convert 'int' object to str implicitly
答案 0 :(得分:4)
您可以明确地将int转换为字符串:
AgeQ = 'Are you ' + str(Age[x]) + 'years old? (Y/N)'
或者更好的是,使用字符串格式:
AgeQ = 'Are you %s years old? (Y/N)' % Age[x]
答案 1 :(得分:3)
AgeQ = 'Are you {age} years old? (Y/N)'.format(age=Age[x])
您不能将字符串与int连接,您必须将int转换为字符串,或以某种方式对其进行格式化。