python3 输出不换行, 同一行刷新显示信息

一般来说,我们使用print时后面都会自动输出一个换行,如何避免呢?

a = 'Hello World'
print(a, end='\n')#这是系统默认的,就是为什么print后面跟一个换行的原因了
1
2
可以进行修改:

a = 'Hello World'
print(a,end='\r')

即可不换行在同一行刷新显示新消息
 

下面是不换行高阶用法

import sys, time

class ProgressBar:
    def __init__(self, count = 0, total = 0, width = 50):
        self.count = count
        self.total = total
        self.width = width
    def move(self):
        self.count += 1
    def log(self, s):
        sys.stdout.write(' ' * (self.width + 9) + '\r')
        sys.stdout.flush()
#        print(s)
#        print('it goes')
        progress = self.width * self.count / self.total
        sys.stdout.write('{0:3}/{1:3}: '.format(self.count, self.total))
        sys.stdout.write('#' * int(progress) + '-' * int(self.width - progress) + '\r')
        if progress == self.width:
            sys.stdout.write('\n')
        sys.stdout.flush()

if __name__ == '__main__':
    bar = ProgressBar(total = 10)
    for i in range(10):
        bar.move()
        bar.log('We have arrived at: ' + str(i + 1))
        time.sleep(1)

 

你可能感兴趣的:(python)