> 文档中心 > 关于 TypeError: can only concatenate str (not “int“) to str

关于 TypeError: can only concatenate str (not “int“) to str

在编写脚本进行字符拼接,运行时出现了 TypeError: can only concatenate str (not “int”) to str

示例代码如下:

name = "neo"age = int(25)money = 9.9if __name__ == '__main__':    print("My name is " + name + ",my age is " + age + ",I have money " + money + " $")

原因分析:

TypeError: can only concatenate str (not "int") to str,意思是不能够把一个整数和字符串进行拼接运算,即 + 运算。

以上文示例代码为例 name = “neo”, 这里 neo 是字符串,而 age = int(25) , 25 是int 类型的数字,无法进行 + 运算操作。如果想要将其进行拼 接在一起进行输出就必须将 age 与 money 的类型进行转换。

正确的运行代码如下:

name = "neo"age = int(25)money = 9.9if __name__ == '__main__':    # print(type(name))    # print(type(age))    # print(type(money))    print("My name is " + name + ",my age is " + str(age) + ",I have money " + str(money) + " $")

狗狗宠物资料大全