如何在不重叠字符串的情况下返回可变长度字符串的输出?

2024-10-03 23:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

当我想改变字符串的长度时,如何使用回车符打印脚本进度的简单信息,同时防止字符串重叠?看看这个简单的例子

import sys
import time
fewds = ["raspberry", "orange", "pineapple", "fig", "honeysuckle"]

for f in fewds:
    sys.stdout.write(f+"\r")
    sys.stdout.flush()
    time.sleep(0.5)

Tags: 字符串import脚本信息timestdoutsysfig
1条回答
网友
1楼 · 发布于 2024-10-03 23:17:42

您可以跟踪打印的最后一行的长度,并使用str.ljust为下一行添加必要的空格,以便完全覆盖上一行

str.ljust(width[, fillchar])

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

所以,你的代码是:

import sys
import time
fewds = ["raspberry", "orange", "pineapple", "fig", "honeysuckle"]

last_length = 0
for f in fewds:
    sys.stdout.write(f.ljust(last_length) + "\r")
    sys.stdout.flush()
    time.sleep(0.5)
    last_length = len(f)

相关问题 更多 >