我想制作一个加载屏幕来执行此操作,但会替换当前行:
LOADING
OADINGL
ADINGLO
DINGLOA
INGLOAD
...
我希望能够控制它一次打印的字母数。我尝试的是:
from itertools import cycle
from time import sleep
itr = cycle('LOADING')
for i in range(10):
sleep(0.3)
print('\r', ''.join(next(itr)))
但结果是:
L
O
A
D
I
N
G
L
O
A
Tags:
直接使用Python切片:
您需要在
print
中使用end
关键字,以避免将每条消息打印到新行。我建议您构建要在每次迭代中显示的字符串,然后显示它。我不喜欢cycle
方法,因为您无法很容易地索引到cycle
对象。相反,我们可以使用常规的字符串索引和模运算符来确保我们不会越界,并且仍然可以一遍遍地“循环”字符串。你知道吗while True
循环的每次迭代都将构建要显示的字符串(在嵌套的for loop
中),然后显示它。在while循环结束时,拥有counter += 1
就足够了,但是对于一个长时间运行的脚本,您可能会得到counter
不必要的大。通过让counter = (counter + 1) % len_msg
,我们可以确保counter
永远不会超过消息的长度。你知道吗相关问题 更多 >
编程相关推荐