Skip to main content
 首页 » 编程设计

python之当某些文本在 python 3 前面时如何打印文本进度条

2025年05月04日14jiqing9006

好吧,我的意思是,这是我的代码:

def progress():                                                                                                                          
    for i in range(100):                                                         
        print('{0}\b\b'.format(i), end='', flush=True)                           
        time.sleep(0.1)                                                          
 
print('progress bar test: {0} finished!'.format(progress()))     

我想要这样的输出:

progress bar test: 1.2.3..(and then print 'finished!') 

但是我还是把它说出来了:

1.2.3... 
progress bar test: None finished! 

这就是问题。而且我也想知道如果数字小于10,\b\b会不会删除前面的文字?

请您参考如下方法:

您的函数未返回值,因此您看到默认返回的 None。您可以在循环完成时返回 "finished":

import time 
def progress(): 
    for i in range(3): 
        print('{0}.'.format(i), end='', flush=True) 
        time.sleep(0.1) 
    return "finished!" 
 
print('progress bar test: {0}'.format(progress())) 

如果您希望能够更改返回值,只需传入一个 arg:

def progress(end): 
    for i in range(3): 
        print('{0}.'.format(i), end='', flush=True) 
        time.sleep(0.1) 
    return end 
 
print('progress bar test: {0} '.format(progress("finished!")))