python - Comment pad zeroes to a string

Mots clés : pythonstringzero-padding

meilleur 5 Réponses python - Comment pad zeroes to a string

vote vote

93

>>> n = '4' >>> print(n.zfill(3)) 004 
>>> n = 4 >>> print(f'{n:03}') # Preferred method, python >= 3.6 004 >>> print('%03d' % n) 004 >>> print(format(n, '03')) # python >= 2.6 004 >>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3 004 >>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3 004 >>> print('{:03d}'.format(n))  # python >= 2.7 + python3 004 
vote vote

81

>>> t = 'test' >>> t.rjust(10, '0') >>> '000000test' 
vote vote

75

print(f'{number:05d}') # (since Python 3.6), or print('{:05d}'.format(number)) # or print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection) print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection) print(format(number, '05d')) 
vote vote

62

>>> i = 1 >>> f"{i:0>2}"  # Works for both numbers and strings. '01' >>> f"{i:02}"  # Works only for numbers. '01' 
>>> "{:0>2}".format("1")  # Works for both numbers and strings. '01' >>> "{:02}".format(1)  # Works only for numbers. '01' 
vote vote

54

>>> '99'.zfill(5) '00099' >>> '99'.rjust(5,'0') '00099' 
>>> '99'.ljust(5,'0') '99000' 

Questions similaires