【问题标题】:How does one use the format() method in python to pad numbers after the E exponent with zeros?如何使用 python 中的 format() 方法在 E 指数之后用零填充数字?
【发布时间】:2015-04-03 19:15:39
【问题描述】:

在阅读了一些关于 .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

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

【问题讨论】:

    标签: python-2.7 string.format


    【解决方案1】:

    看来这只是不可能通过单个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'
    

    【讨论】:

      【解决方案2】:

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

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

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

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

      但总的来说,它可能会产生错位。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2016-06-15
        • 2013-08-09
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多