【问题标题】:Using .format() in Python to allign a mix of variables and characters在 Python 中使用 .format() 来对齐变量和字符的混合
【发布时间】:2016-11-04 18:51:06
【问题描述】:

我正在尝试学习如何使用 Python 的 .format() 使我正在编写的测试的控制台输出看起来更具可读性,但我还没有完全理解它。

我目前的尝试是这样的:

print('({:d}/{:d}) {} {} {} {}'.format(test, num_tests, *item))

它可以很好地打印出我想要的内容,但我想对齐这些不同的字段,以便无论数字有多少,它们总是对齐。例如,我当前的输出如下所示:

(9/800) item1 item2 item3 item4
(10/800) item1 item2 item3 item4

有没有办法可以重写我的格式,让它看起来像这样?

 (9/800) item1 item2 item3 item4
(10/800) item1 item2 item3 item4

【问题讨论】:

  • 我认为这是不可能的,除非您提前知道特定字段的最大可能大小,我认为情况并非如此,因为您说“无论有多少位数.. ."。假设这两个后面的行是“(99999999999/800)”。 Python 无法返回并重写它已经打印的行以添加更多空格。 (如果你使用 curses 或类似的,也许可以,但不是每个控制台都会支持)
  • 所以我可以放心地假设第一个数字永远不会比第二个数字多。我也可以假设 num_tests 永远不会超过 5 位数。我不需要它完全灵活。
  • 如果你知道编译时的最大尺寸,你可以在格式字符串中手动指定宽度:print('({:3d}/...。在运行时将第一个字段的 with 设置为第二个字段的长度会有点棘手。
  • 除了左括号和第一个数字之间可能存在很大的空间之外,这很好用。我是唯一一个会看到这个的人,所以这并不重要,但感谢您的帮助。

标签: python python-3.x string-formatting string.format


【解决方案1】:

试试:

print('({:>3}/{}) {} {} {} {}'.format(test, num_tests, *item))

例子:

>>> print('({:>3}/{}) {} {} {} {}'.format(0, 800, 1, 2, 3, 4))
(  0/800) 1 2 3 4
>>> print('({:>3}/{}) {} {} {} {}'.format(10, 800, 1, 2, 3, 4))
( 10/800) 1 2 3 4
>>> print('({:>3}/{}) {} {} {} {}'.format(100, 800, 1, 2, 3, 4))
(100/800) 1 2 3 4

其他例子:

>>> print('({:>3}/{}) {:>12} {:>12} {:>12} {:>12}'.format(1, 800, 'Python', 'Hello', 'World', '!'))
(  1/800)       Python        Hello        World            !
>>> print('({:>3}/{}) {:>12} {:>12} {:>12} {:>12}'.format(100, 800, 'I', 'Love', 'Python', '!'))
(100/800)            I         Love       Python            !

或者

>>> print('({:03d}/{}) {:>12} {:>12} {:>12} {:>12}'.format(12, 800, 'I', 'Love', 'Python', '!'))
(012/800)            I         Love       Python            !

【讨论】:

  • 看起来不错。只是想知道是否有一种简单的方法可以删除左括号后的多余空格。
  • 新例子,你可以使用:{:>3} -> (012/800)
  • {:03d} -> (012/800)
【解决方案2】:

您可以创建一个自定义函数并设置str.rjust() 以设置要包装的文本的长度。您的自定义函数可以是:

def my_print(test, num_tests, *item):
    width = 8 
    test = '({:d}/{:d})'.format(test, num_tests).rjust(width)
    items = ''.join(str(i).rjust(width) for i in item)
    print test + items

示例运行:

>>> my_print(9, 800, 'yes', 'no', 'hello')
 (9/800)     yes      no   hello

如果必须通过str.format() 进行,您可以创建自定义函数来添加填充:

def my_print(test, num_tests, *item):
    test = '{0: >10}'.format('({:d}/{:d})'.format(test, num_tests))
    items = ''.join('{0: >6}'.format(i) for i in item)
    print test + items

示例运行:

>>> my_print(9, 800, 'yes', 'no', 'hello')
   (9/800)   yes    no hello

查看String Format Specification 文档以获取所有格式选项的列表。

【讨论】:

  • 我希望有一种方法可以使用 .format() 来实现,但这会很好。谢谢!
  • 哦,我从来没有想过我可以格式化格式。这很酷。
猜你喜欢
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多