Python错误TypeError:只能将str(而不是“int”)连接到str

2024-04-25 02:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是这个地区的新手,帮我找出错误

name = input( "Enter your name:"  ) 
age = 12
print( "Hi, " + name + " " + age + " years old!" )

$ python test.py
Enter your name:evgen
Traceback (most recent call last):
File "test.py", line 5, in <module>
print( "Hi, " + name + " " + age + " years old!" )
TypeError: can only concatenate str (not "int") to str

Tags: namepytestinputageyour错误hi
2条回答

在连接之前,需要将int转换为str:

name = input( "Enter your name:"  ) 
age = 12
print( "Hi, " + name + " " + str(age) + " years old!" )

还可以看看python的字符串格式化:https://docs.python.org/3.4/library/string.html#format-examples

您正在将字符串与整数age连接起来。简单地将age转换为str,如下所示:

print( "Hi, " + name + " " +str(age) + " years old!" )

相关问题 更多 >