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

Python进度条完成后显示多余百分号问题求助

Python进度条完成时出现多余百分号的修复方案

问题根源

  1. 格式字符串不统一:黄色进度条的百分比格式为{percent: .0f}%(数字前带空格),而绿色完成态的格式为{percent:.0f}%(无空格),导致两者输出长度不一致。当绿色进度条覆盖黄色进度条时,较短的绿色字符串无法完全覆盖原黄色进度条的内容,残留了一个%符号,最终显示为100%%。
  2. 结束符设置错误:完成态进度条使用end="\r"会让光标停留在行首,后续的颜色重置语句会自动换行,导致显示异常。

修复后的代码

import math
import colorama

def progress_bar(progress, total, color=colorama.Fore.YELLOW):
    percent = 100 * (progress / float(total))
    bar = '■' * int(percent) + '-' * (100 - int(percent))
    # 统一百分比格式,避免长度差异
    percent_str = f"{percent:.0f}%"
    print(color + f"\r|{bar}| {percent_str}", end="\r")
    if progress == total:
        # 完成时切换绿色,并将光标移到下一行
        print(colorama.Fore.GREEN + f"\r|{bar}| {percent_str}", end="\n")

numbers = [x * 5 for x in range(1000)]
results = []
progress_bar(0, len(numbers))
for i, x in enumerate(numbers):
    results.append(math.factorial(x))
    progress_bar(i + 1, len(numbers))
print(colorama.Fore.RESET)

核心修复点

  • 统一格式:将两种状态的百分比格式统一为{percent:.0f}%,确保输出长度一致,彻底解决覆盖残留问题。
  • 调整结束符:完成态进度条使用end="\n"代替end="\r",让光标移到新行,避免后续颜色重置干扰进度条显示。
  • 可选优化(简化代码):将颜色和结束符的判断逻辑合并,减少冗余代码:
def progress_bar(progress, total):
    percent = 100 * (progress / float(total))
    bar = '■' * int(percent) + '-' * (100 - int(percent))
    percent_str = f"{percent:.0f}%"
    # 根据进度状态选择颜色和结束符
    color = colorama.Fore.GREEN if progress == total else colorama.Fore.YELLOW
    end_char = "\n" if progress == total else "\r"
    print(color + f"\r|{bar}| {percent_str}", end=end_char)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:40:20