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

Python中拼接int与str触发TypeError:不支持+运算符该如何解决?

Python拼接整数与字符串时的TypeError解决方法

在Python中,你不能直接用+运算符拼接字符串(str类型)和整数(int类型),这就是触发错误的核心原因。

错误代码

number = 5
message = "The number is: " + number
print(message)

错误信息

TypeError: unsupported operand type(s) for +: 'int' and 'str'

解决方法

以下是几种可行的修复方式,都能输出你预期的The number is: 5:

  • 将整数转换为字符串后拼接
    使用str()函数把整数转为字符串类型,再执行拼接操作:

    number = 5
    message = "The number is: " + str(number)
    print(message)
    
  • 使用f-string(推荐,Python 3.6及以上版本)
    f-string是Python中最简洁直观的字符串格式化方式,会自动处理变量的类型转换:

    number = 5
    message = f"The number is: {number}"
    print(message)
    
  • 使用str.format()方法
    通过占位符{}来替换变量,同样能自动处理类型:

    number = 5
    message = "The number is: {}".format(number)
    print(message)
    
  • 使用%格式化操作符
    这是一种传统的字符串格式化方式,%d用于匹配整数:

    number = 5
    message = "The number is: %d" % number
    print(message)
    

内容的提问来源于stack exchange,提问作者Shreya Tripathi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:42:13