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

Python如何在字符串后同一行打印数字求和结果

你写的代码存在两处错误:

  • 赋值操作score=score+1不能直接放在+拼接符后参与字符串运算
  • 数字类型的score不能直接和字符串拼接,需要先做类型转换

以下是几种可直接运行的修改方案:

方案1:通用字符串拼接方案(兼容所有Python版本)

# 先更新score的值
score = score + 1
# 把score转成字符串后再拼接
print("Your answer is correct, this is your score:" + str(score))

方案2:f-string方案(Python3.6及以上版本推荐,写法最简洁)

不需要手动做类型转换,代码可读性更高:

score += 1
print(f"Your answer is correct, this is your score:{score}")

如果不需要保留更新后的score值,也可以直接把求和逻辑写在占位符中:

print(f"Your answer is correct, this is your score:{score + 1}")

方案3:print多参数输出方案

利用print的多参数特性,设置分隔符为空即可避免手动拼接:

score += 1
print("Your answer is correct, this is your score:", score, sep='')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:57:06