【问题标题】:printf formatting of strings in python [duplicate]python中字符串的printf格式[重复]
【发布时间】:2017-06-22 23:08:08
【问题描述】:

有没有办法在 Python 中对字符串进行printf 格式化?就像这样,每次都会重写计数 x,而不是回显到新行。

x=0
while [[ $x -lt 10 ]]; do
    x=$((x+1))
    printf '%s\r'"Processing page ${x}"
    sleep 1
done

【问题讨论】:

  • 你的意思是像this
  • 这个问题的答案取决于使用的 Python 版本。你用的是 Python2 还是 Python3?
  • @Robᵩ 我正在使用 Python2
  • 谢谢,链接的问题给了我答案。

标签: python bash formatting


【解决方案1】:

在 Python 3.x 中,打印函数为 end 参数接收一个附加参数。

>>> print('foo', end='')
foo

>>> for i in range(10):
print('foo', end='')
foofoofoofoofoofoofoofoofoofoo

当然,如果您使用 Python >= 2.6,则需要从 __future__ 导入 print_function

>>> from __future__ import print_function

【讨论】:

  • 感谢您的帮助。
【解决方案2】:

在 Python 3 中(Daiwei Chen 的回答也涵盖 Python 2.6+):

import time
x = 0
while x < 10:
    x += 1
    print('\rProcessing Page {0}'.format(x), end='')
    time.sleep(1)

在开头添加回车并使用end='' 从末尾删除新行将覆盖当前行。

【讨论】:

  • 您可能会提到您的解决方案特定于 Python3,或者(甚至更好)提供适用于 Python2 和 Python3 的解决方案。
  • 是的,刚才我想起来了
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多