How do I format a number with a variable number of digits in Python?

后端 未结 7 887
攒了一身酷
攒了一身酷 2020-12-07 12:23

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits =

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 12:38

    If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

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

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

    Here is an example with variable width

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

    You can even specify the fill char as a variable

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

提交回复
热议问题