【问题标题】:print with line replacement in python [duplicate]在python中使用换行打印[重复]
【发布时间】:2020-02-20 20:43:46
【问题描述】:

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

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

附:我看到了 Link 但它没有给我答案 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 ...

【问题讨论】:

  • 您可以打印"\r"(或将其发送到sys.stdout)以返回到行首,但您需要在终端中运行代码才能看到...
  • “由于某种原因无法工作”是什么意思?它会引发错误吗?是否重置光标失败?
  • 获得该输出的原因是因为“Good Bye”打印在同一行...改用print("\nGood bye")...
  • 如果要在准备覆盖当前行之后 打印新行,则必须先打印显式换行符 (\n)。
  • 我看到了@EdWard,\n 有魔力

标签: python-3.x


【解决方案1】:

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

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 中添加一个换行符 (\n),而不是一个空的 print,使其成为:

print('\nGood Bye')

但孤立的print() 对意图更清楚一些,不需要使用常量或字符串格式等。

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多