【问题标题】:How do I format a number with a variable number of digits in Python?如何在 Python 中格式化具有可变位数的数字?
【发布时间】:2011-03-14 19:40:19
【问题描述】:

假设我想在前面显示数字 123,并在前面填充可变数量的零。

例如,如果我想以 5 位数字显示它,我将有 digits = 5 给我:

00123

如果我想以 6 位数字显示它,我会给出 digits = 6:

000123

我将如何在 Python 中做到这一点?

【问题讨论】:

    标签: python string string-formatting number-formatting


    【解决方案1】:

    如果您在格式化字符串中使用format() 方法,该方法优于旧式''% 格式

    >>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
    'One hundred and twenty three with three leading zeros 000123.'
    


    http://docs.python.org/library/stdtypes.html#str.format
    http://docs.python.org/library/string.html#formatstrings

    这是一个可变宽度的示例

    >>> '{num:0{width}}'.format(num=123, width=6)
    '000123'
    

    您甚至可以将填充字符指定为变量

    >>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
    '000123'
    

    【讨论】:

    • +1 用于提及新的格式方法。需要一点时间来适应,但我实际上觉得它比旧的% 样式更干净,这对我来说很讽刺,因为我曾经觉得% 样式是最干净的方法。
    • 还支持未命名的位置文件夹(至少在 Python 3.4 中):"{:{}{}}".format(123, 0, 6).
    • @CoDEmanX 未命名的占位符也适用于 python 2.7 - 谢谢。
    • 随着 Python 3.6 中 f-strings 的引入,现在可以访问以前定义的变量而无需 .format。只需在字符串前面加上 ff'{num:{fill}{width}}'。我用这个信息添加了一个答案。
    【解决方案2】:

    有一个叫zfill的字符串方法:

    >>> '12344'.zfill(10)
    0000012344
    

    它将用零填充字符串的左侧以使字符串长度为 N(在本例中为 10)。

    【讨论】:

    • 这正是我正在寻找的,我只是做 '123'.zfill(m) 这允许我使用变量而不是具有预定位数。谢谢!
    【解决方案3】:
    '%0*d' % (5, 123)
    

    【讨论】:

    【解决方案4】:

    使用 Python 3.6 中的the introduction of formatted string literals(简称“f-strings”),现在可以使用更简洁的语法访问之前定义的变量:

    >>> name = "Fred"
    >>> f"He said his name is {name}."
    'He said his name is Fred.'
    

    John La Rooy 给出的例子可以写成

    In [1]: num=123
       ...: fill='0'
       ...: width=6
       ...: f'{num:{fill}{width}}'
    
    Out[1]: '000123'
    

    【讨论】:

      【解决方案5】:

      对于那些想用 python 3.6+ 和f-Strings 做同样事情的人来说,这就是解决方案。

      width = 20
      py, vg = "Python", "Very Good"
      print(f"{py:>{width}s} : {vg:>{width}s}")
      

      【讨论】:

      • s 是什么?
      【解决方案6】:
      print "%03d" % (43)
      

      打印

      043

      【讨论】:

        【解决方案7】:

        使用字符串格式

        print '%(#)03d' % {'#': 2}
        002
        print '%(#)06d' % {'#': 123}
        000123
        

        更多信息在这里:link text

        【讨论】:

          猜你喜欢
          • 2014-05-27
          • 2013-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-25
          相关资源
          最近更新 更多