如何使用 python 中的 format() 方法用零填充 E 指数后的数字?

How does one use the format() method in python to pad numbers after the E exponent with zeros?

在阅读了一些关于 .format 的文档并开发了这段代码后,我几乎成功地将我的数字输出格式化为我需要的格式:

timepoint = 6
strTimepoint = "{:1.7E}".format(timepoint)

因此打印 strTimepoint 将发出此消息:

# with timepoint = 6
>>6.0000000E+00
# with timepoint = 12
>>1.2000000E+01

等等。

要使它成为我需要的字符串,我唯一需要做的就是将指数数字用零填充为三位数,因此:

# timepoint = 6
>>6.0000000E+000
# timepoint = 12 
>>1.2000000E+001

事后我不能简单地用零填充,因为它需要适应要求高于个位数指数的数字。 我找不到这方面的文档,所以关于这个主题的任何帮助都是有帮助的,谢谢。

看来单次 str.format 调用是不可能的。

它不会那么漂亮,但您可以简单地添加另一个:

# Regular Python's scientific notation, split up to coefficient and exponent.
x, e = "{:1.7E}".format(timepoint).split("E")

# Format again: coefficient first, then sign, then padded "sign-less" exponent.
strTimepoint = "{}E{}{:0>3}".format(x, e[0], e[1:])

当然,强烈建议将其全部包装在一个函数中(根据您的需要调整名称):

def foo(timepoint):
    # Regular Python's scientific notation, split up to coefficient and
    # exponent.
    x, e = "{:1.7E}".format(timepoint).split("E")

    # Format again: coefficient first, then sign, then padded "sign-less"
    # exponent.
    return "{}E{}{:0>3}".format(x, e[0], e[1:])


foo(6)  # '6.0000000E+000'
foo(12)  # '1.2000000E+001'
foo(1e123)  # '1.0000000E+123'

您可以使用 re.sub 在事实之后插入 0,但在发生替换的情况下,它会产生将字符串加长一个字符的效果:

>>> re.compile("(E[-+])(\d\d)$").sub(r'\g<1>0',"{:7.1E}".format(6E19))
'6.0E+019'

对于 7.1 格式,这不是问题,因为如果指数为三位数,则最小字段长度为 8:

>>> re.compile("(E[-+])(\d\d)$").sub(r'\g<1>0',"{:7.1E}".format(6E190))
'6.0E+190'

但一般来说,它可能会产生错位。

(当然,在实际代码中,您只会编译该正则表达式一次,而不是每次都进行转换。)