用Python格式化表格格式的文本
使用用Python格式化表格格式的文本,python,string,python-3.x,format,Python,String,Python 3.x,Format,使用string.format插入多个数据项。然后,控制台的输出如下所示: propertiesTextBlock = """ Basic Properties ---------------- - nodes (n) {n} - edges (m) {m} - min. degree {minDeg} - max. degree {maxDeg} - isolated
string.format
插入多个数据项。然后,控制台的输出如下所示:
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}
"""
不完美,因为我需要在文本块中手动插入正确数量的选项卡。另外,如果我想以不同的方式对齐数字(例如右对齐,在
处对齐……),该怎么办
有没有一种简单的方法可以确保这张桌子看起来漂亮?正确的答案可能是使用或
如果您想保持纯旧格式,可以控制字段宽度:
Basic Properties
----------------
- nodes (n) 10680
- edges (m) 24316
- min. degree 1
- max. degree 205
- isolated nodes 0
- self-loops 0
- density 0.000426
对于浮点值,可以与小数点对齐:
>>> 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
>20
格式规范将字段宽度设置为20个字符,并右对齐该字段中的值
但是,这不支持按小数点对齐。您可以通过以下方式指定动态字段宽度:
>>> print '- nodes (n) {n:>20}\n- edges (m) {m:>20}'.format(n=1234, m=234)
- nodes (n) 1234
- edges (m) 234
您可以对其进行调整,以添加或删除浮点数周围的空白:
>>> 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
这里,根据整个值将占用的空间大小,调整字段宽度以向左或向右移动小数点。请注意,字段宽度是总宽度,因此包括小数点和6位小数。是否可以使用格式而不是此表格形式?@alecxe理想情况下,我希望输出为降价格式。prettytable与之兼容吗?你知道格式语法支持文本左对齐或右对齐吗?@cls nope,prettytable只是用于可视化tables@cls另外看一下模块,可能会有所帮助。
>>> 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