You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字符串与整数拼接报错求助:解决TypeError问题

问题解决:字符串与整数拼接的TypeError错误

错误原因

你尝试用+运算符拼接字符串类型的name和整数类型的age,但Python不允许直接将字符串与整数进行拼接操作,因此抛出了TypeError: can only concatenate str (not "int") to str错误。

解决方法

以下是几种可行的修复方案:

方法1:将整数转为字符串

使用str()函数把整数age转换为字符串类型后再拼接:

name = 'mahbod'
age = 12
print(name + str(age))

方法2:使用f-string格式化(Python3.6+推荐)

通过f-string直接在字符串中嵌入变量,Python会自动处理类型转换:

name = 'mahbod'
age = 12
print(f"{name}{age}")
# 如需添加分隔符(比如空格),可改为:print(f"{name} {age}")

方法3:利用print函数的多参数特性

print函数支持传入多个参数,默认用空格分隔,无需手动拼接:

name = 'mahbod'
age = 12
print(name, age)

方法4:使用format()方法(兼容性更广)

这是适用于多数Python版本的字符串格式化方式:

name = 'mahbod'
age = 12
print("{}{}".format(name, age))

内容的提问来源于stack exchange,提问作者mahbod yari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 21:48:19