Fixed width number formatting python 3

后端 未结 3 413
Happy的楠姐
Happy的楠姐 2021-01-31 19:06

How do I get an integer to fill 0\'s to a fixed width in python 3.2 using the format attribute? Example:

a = 1
print(\'{0:3}\'.format(a))

gives

相关标签:
3条回答
  • 2021-01-31 19:45

    Prefix the width with a 0:

    >>> '{0:03}'.format(1)
    '001'
    

    Also, you don't need the place-marker in recent versions of Python (not sure which, but at least 2.7 and 3.1):

    >>> '{:03}'.format(1)
    '001'
    
    0 讨论(0)
  • 2021-01-31 19:48

    There is built-in string method .zfill for filling 0-s:

    >>> str(42).zfill(5)
    '00042'
    >>> str(42).zfill(2)
    '42'
    
    0 讨论(0)
  • 2021-01-31 19:54

    Better:

    number=12
    print(f'number is equal to {number:03d}')
    
    0 讨论(0)
提交回复
热议问题