首页 > 解决方案 > 在python中用换行打印

问题描述

我喜欢打印一些东西,然后用下一个值替换它,这样以前的值就会消失,新的值会替换它。我该怎么做?例如在

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i)) # I like to print with replacement here

print('Good Bye')

我喜欢这样的最终输出:

Hello World
Case Number 9
Good Bye

PS我看到了链接,但它没有给我答案print('Case Number {} ...'.format(i), end='\r')由于某种原因不起作用。具体来说:

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i), end='\r') # I like to print with replacement here

print('Good Bye')

将产生:

Hello World
Good Byeber 9 ...

标签: python-3.x

解决方案


完成所有就地重写后,打印一个额外的新行:

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i), end='\r') # I like to print with replacement here

print()  # Move to next line
print('Good Bye')  # Now print

print您可以在最后的字符串前面加上print换行符( ),而不是空的\n,使其成为:

print('\nGood Bye')

但是隔离print()的意图更清楚一些,并且不需要使用常量或字符串格式等进行处理。


推荐阅读