1
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

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

4

2 回答 2

2

您可以使用格式迷你语言来指定对齐方式:

>>> 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 位小数。

于 2013-08-14T13:34:54.083 回答
1

正确的答案可能是使用prettytableor tabulate

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

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

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

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

于 2013-08-14T13:18:16.043 回答