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

如何移除Python循环中单行打印输出末尾的多余空格?

循环打印移除末尾多余空格的解决方法
  • 方法1:预生成所有格式化内容,用join拼接后一次性打印(最推荐写法)
    先把所有要输出的内容整理为字符串列表,用空格作为分隔符拼接后打印,天然不会产生末尾多余空格:
    import math
    
    f0 = int(input())
    r = math.pow(2, 1/12)
    result_list = []
    for i in range(5):
        f1 = f0 * (r ** i)
        result_list.append('{:.2f}'.format(f1))
    print(' '.join(result_list))
    
  • 方法2:循环内判断是否为最后一个元素,动态调整end参数
    如果要保留循环内打印的逻辑,只需要在最后一次打印时不指定end=' ',用默认的换行即可:
    import math
    
    f0 = int(input())
    r = math.pow(2, 1/12)
    count = 5
    for i in range(count):
        f1 = f0 * (r ** i)
        if i == count - 1:
            print('{:.2f}'.format(f1))
        else:
            print('{:.2f}'.format(f1), end=' ')
    
  • 方法3:整体拼接后用rstrip()移除右侧末尾空格
    你之前用strip()会移除所有首尾空格,改用rstrip()只会移除末尾的空格,不会影响内容中间的分隔空格:
    import math
    
    f0 = int(input())
    r = math.pow(2, 1/12)
    full_output = ''
    for i in range(5):
        f1 = f0 * (r ** i )
        full_output += '{:.2f} '.format(f1)
    print(full_output.rstrip())
    

内容的提问来源于stack exchange,提问作者सृजन सृजन

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:39:00