如何居中对齐numpy.savetxt生成的文本?

时间:2013-03-21 18:38:03

标签: python numpy alignment center

我在numpy.savetxt周围使用一个小包装器来自动生成标题名称,并为可读输出创建一些智能宽度对齐。更准确的解决方案是this answer

我想知道如何指定宽度并使输出文本与中心对齐,而不是像文档中所示左对齐。

numpy.savetxt文档中,我看到了以下信息:

Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):
flags:
    ``-`` : left justify

    ``+`` : Forces to preceed result with + or -.

    ``0`` : Left pad the number with zeros instead of space (see width).

width:
    Minimum number of characters to be printed. The value is not truncated
    if it has more characters.

文档指向python mini format specification处的更为“详尽的资源”,但其中的信息与对齐信息不兼容。

  

各种对齐选项的含义如下:

Option  Meaning
'<'     Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'     Forces the field to be right-aligned within the available space (this is the default for numbers).
'='     Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^'     Forces the field to be centered within the available space.

不兼容是因为savetxt不接受'^'作为有效的格式化字符。任何人都可以说明如何在`numpy.savetxt'中指定格式,以便输出中心对齐?

1 个答案:

答案 0 :(得分:1)

您可以使用'^'组合更复杂的格式选项,包括居中的format标记:

import numpy as np
a = np.ones((3,3))*100
a[1,1]=111.12321
a[2,2]=1
np.savetxt('tmp.txt',a, fmt='{:*^10}'.format('%f'))

,并提供:

****100.000000**** ****100.000000**** ****100.000000****
****100.000000**** ****111.123210**** ****100.000000****
****100.000000**** ****100.000000**** ****1.000000****