Home >Backend Development >Python Tutorial >How Can I Pad Strings and Numbers with Leading Zeros in Python?
String Padding with Zeros
Adding zeros to the left of a string to reach a specific length is a common task in programming. This technique is useful for formatting numeric values, ensuring consistent field widths, and other applications.
String Padding
To pad strings with zeros, Python provides the zfill() method. For instance, if we have a string n = '4', we can pad it to a length of 3 zeros as follows:
n = '4' print(n.zfill(3)) # Output: 004
Number Padding
Padding numbers is similar to padding strings. However, Python offers several methods to achieve this. One preferred method, available in Python 3.6 and later, is using the f-string syntax:
n = 4 print(f'{n:03}') # Output: 004
Alternatively, you can use the % operator:
print('%03d' % n) # Output: 004
Or the format() function:
print(format(n, '03')) # Output: 004 print('{0:03d}'.format(n)) # Output: 004
For advanced use cases, you can specify additional parameters within the formatting string to control various aspects of the padding. Refer to the String Formatting documentation for more information.
The above is the detailed content of How Can I Pad Strings and Numbers with Leading Zeros in Python?. For more information, please follow other related articles on the PHP Chinese website!