使用Python以表格形式格式化文本 [英] Formatting text in tabular form with Python

查看:360
本文介绍了使用Python以表格形式格式化文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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插入多个数据项.输出到控制台,如下所示:

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?

推荐答案

您可以使用

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

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

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

此处,将根据整个值要占用的空间来调整字段宽度,以使小数点向左或向右移动.请注意,字段宽度是宽度,因此包括小数点和6位小数.

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.

这篇关于使用Python以表格形式格式化文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆