【问题标题】:Formatting text in tabular form with Python使用 Python 以表格形式格式化文本
【发布时间】:2013-08-16 11:02:39
【问题描述】:
propertiesTextBlock = """
    Basic Properties
    ----------------
    - nodes (n)         {n}
    - edges (m)         {m}
    - min. degree           {minDeg}
    - max. degree           {maxDeg}
    - isolated nodes        {isolates}
    - self-loops            {loops}
    - density           {dens:10.6f}
"""

使用string.format 插入了几个数据项。输出到控制台然后看起来像:

Basic Properties
----------------
- nodes (n)         10680
- edges (m)         24316
- min. degree           1
- max. degree           205
- isolated nodes        0
- self-loops            0
- density             0.000426

并不完美,因为我需要在文本块中手动插入正确数量的标签。另外,如果我想以不同的方式对齐数字怎么办(例如右对齐所有内容,对齐. ...) 有没有一种简单的方法可以确保这张桌子看起来不错?

【问题讨论】:

  • 您可以使用prettytable 格式代替此表格形式吗?
  • @alecxe 理想情况下,我希望输出为降价格式。 Prettytable 与它兼容吗?
  • 你知道格式语法支持文本左右对齐吗?
  • @cls nope,prettytable 只是用于可视化表格
  • @cls 也看看tabulate 模块,可能会有所帮助。

标签: python string python-3.x format


【解决方案1】:

您可以使用format mini language 指定对齐方式:

>>> print '- nodes (n) {n:>20}\n- edges (m) {m:>20}'.format(n=1234, m=234)
- nodes (n)                 1234
- edges (m)                  234

>20 格式规范将字段宽度设置为 20 个字符并右对齐该字段中的值。

这确实支持小数点对齐,但是。您可以指定动态字段宽度:

>>> print '- nodes (n) {n:>{width}}'.format(n=123, width=5)
- nodes (n)   123
>>> print '- nodes (n) {n:>{width}}'.format(n=123, width=10)
- nodes (n)        123

你可以适应在浮点数周围添加或删除空格:

>>> from math import log10
>>> print '- density {density:>{width}.6f}'.format(density=density, width=10-int(log10(int(density))))
- density  0.000426
>>> density = 10.000426
>>> print '- density {density:>{width}.6f}'.format(density=density, width=10-int(log10(int(density))))
- density 10.000426

这里的字段宽度被调整为根据整个值将占用多少空间向左或向右移动小数点。注意字段宽度是宽度,所以包括小数点和6位小数。

【讨论】:

    【解决方案2】:

    正确的答案可能是使用prettytabletabulate

    如果你想保持简单的旧格式,你可以控制字段宽度:

    >>> print "node:{0:16}".format(10680,);
    node:           10680
    #    ^^^^^^^^^^^^^^^^ 
    #      16 characters
    

    对于 float 值,您可以对齐到小数点:

    >>> print "node:{0:16.2f}".format(10680.); \
    ... print "node:{0:16.2f}".format(10.5)
    ... print "node:{0:16.2f}".format(123.456)
    node:        10680.00
    node:           10.50
    node:          123.46
    #    ^^^^^^^^^^^^^^^^ 
    #      16 characters
    

    这里是“格式迷你语言”的正式描述:http://docs.python.org/2/library/string.html#formatstrings

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2013-04-13
      • 2012-02-29
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多