Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python错误类型错误:只能将str(而不是“int”连接到str_Python_Python 3.x - Fatal编程技术网

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

Python错误类型错误:只能将str(而不是“int”连接到str,python,python-3.x,Python,Python 3.x,我是这个地区的新手,帮我找出错误 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, " + nam

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

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
name=input(“输入您的姓名:”)
年龄=12
打印(“嗨,”+姓名+“+年龄+”岁!”)
$python test.py
输入您的姓名:evgen
回溯(最近一次呼叫最后一次):
文件“test.py”,第5行,在
打印(“嗨,”+姓名+“+年龄+”岁!”)
TypeError:只能将str(而不是“int”)连接到str

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

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

还可以看看python中的字符串格式:

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

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

这不是python中字符串转换的工作方式。是的,我对它进行了糟糕的编辑。前面的括号方法在php中有效。所以我把语法搞糊涂了!一种更“现代”且更简单的处理字符串的方法是使用格式。特别是
f-strings
print(f“Hi,{name}{age}year!”)