Formatting text in tabular form with Python

2019-07-31 04:52发布

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}
"""

Several data items are inserted using string.format. Output to console then looks like:

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

Not perfect, because I need to manually insert exactly the right amount of tabs in the text block. Also, what if I want to align the numbers differently (e.g right-justify everything, align at . ...) Is there an easy way to make sure that this table looks nice?

2条回答
别忘想泡老子
2楼-- · 2019-07-31 05:20

You can use the format mini language to specify alignments:

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

The >20 formatting specification sets the field width to 20 characters and right-aligns the value in that field.

This does not support alignment by decimal point, however. You can specify dynamic field widths though:

>>> 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

which you can adapt to add or remove whitespace around a floating point number:

>>> 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

Here the field width is adjusted to shift the decimal point left or right based on how much space the whole value is going to take. Note that the field width is the total width, so including the decimal point and the 6 decimals.

查看更多
爷的心禁止访问
3楼-- · 2019-07-31 05:35

The right answer is maybe to use prettytable or tabulate.

If you want to stay with plain old format, you could control field width:

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

For float values you could align to the decimal point:

>>> 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

Here is the formal description of the "format mini-language": http://docs.python.org/2/library/string.html#formatstrings

查看更多
登录 后发表回答