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

无法将字符串与两个int类型变量的和拼接并打印问题求助

问题解决:字符串与整数拼接报错

你这段代码运行会报错,核心原因是Python不允许直接拼接字符串和整数类型的数据——apple是字符串,x+y计算后得到的是整数30,两种不同类型不能用+直接连接。

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

  • 方法1:将整数转为字符串
    用str()函数把相加后的整数转换成字符串类型,再和原字符串拼接:

    x = 10
    y = 20
    apple = "Number of apples "
    
    sentence = apple + str(x+y)
    print(sentence)  # 输出:Number of apples 30
    
  • 方法2:使用f-string(Python 3.6及以上版本推荐)
    直接在字符串里嵌入表达式,写法简洁又直观:

    x = 10
    y = 20
    apple = "Number of apples "
    
    sentence = f"{apple}{x+y}"
    # 也可以直接把所有内容整合到f-string里
    sentence = f"Number of apples {x+y}"
    print(sentence)
    
  • 方法3:使用str.format()方法
    通过占位符替换的方式完成拼接,兼容性更好:

    x = 10
    y = 20
    apple = "Number of apples "
    
    sentence = "{}{}".format(apple, x+y)
    print(sentence)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:09:28