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

后端 未结 7 759
攒了一身酷
攒了一身酷 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:59

    With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax:

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

    The examples given by John La Rooy can be written as

    In [1]: num=123
       ...: fill='0'
       ...: width=6
       ...: f'{num:{fill}{width}}'
    
    Out[1]: '000123'
    
    0 讨论(0)
提交回复
热议问题