Home >Backend Development >Python Tutorial >How Can I Add Leading Zeros to Numeric Strings in Python?
Zero-Padding Numeric Strings
To add leading zeros to a numeric string, enhancing its length, multiple approaches can be employed in Python:
Padding Strings:
For string padding, the zfill method is utilized:
n = '4' print(n.zfill(3)) # Output: 004
Padding Numbers:
Various methods can be used to pad numbers:
n = 4 print(f'{n:03}') # Output: 004
print('%03d' % n) # Output: 004
print(format(n, '03')) # Output: 004 print('{0:03d}'.format(n)) # Output: 004 print('{foo:03d}'.format(foo=n)) # Output: 004
print('{:03d}'.format(n)) # Output: 004
Consult the String Formatting documentation for further details.
The above is the detailed content of How Can I Add Leading Zeros to Numeric Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!