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

Python打印结果中等号前多出多余加号的解决方法问询

解决方案

你可以通过两种常用方式解决这个问题:

方式1:打印时清理末尾多余的加号和空格

只需要修改print语句,使用字符串的rstrip()方法移除末尾连续的加号和空格即可,修改后完整代码如下:

until = int(input("Until: "))
number = 1
result = 1
calculation = ""

while result < until:
    number += 1
    result = result + number
    calculation += f"{number} + "
    # 清理末尾多余的加号和空格
    print(f"Calculated {calculation.rstrip(' + ')} = {result}")

方式2:用列表存储运算数,拼接时自动处理分隔符

这种方式更符合Python最佳实践,避免后续手动清理字符串,逻辑更清晰:

until = int(input("Until: "))
number = 1
result = 1
# 改用列表存储每个运算数字
calculation = []

while result < until:
    number += 1
    result = result + number
    calculation.append(str(number))
    # 用 ' + ' 拼接列表所有元素,自动不会生成末尾多余加号
    print(f"Calculated {' + '.join(calculation)} = {result}")

两种方式运行后输出均符合预期:

Until: 10
Calculated 2 = 3
Calculated 2 + 3 = 6
Calculated 2 + 3 + 4 = 10

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:39:02