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

2024-06-01 06:42:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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处指向一个更“详尽的资源”,但是那里的信息与对齐信息不兼容。在

The meaning of the various alignment options is as follows:

^{pr2}$

不兼容是因为savetxt不接受'^'作为有效的格式化字符。有人能解释一下如何指定格式吗`numpy.savetxt'以便输出居中对齐?在


Tags: oftheto文档numpy信息number宽度
1条回答
网友
1楼 · 发布于 2024-06-01 06:42:59

可以使用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'))

给予:

^{pr2}$

相关问题 更多 >