Home >Backend Development >Python Tutorial >How to Pad Strings and Numbers with Zeros in Python?
Padding Strings with Zeros
In Python, strings and numbers can be padded with zeros to a specific length. Here's how to achieve this:
Padding Strings
To pad a string with zeros, use the zfill() method. For example:
n = '4' print(n.zfill(3)) # Output: 004
This will pad the string with zeros until it reaches the specified length.
Padding Numbers
Numbers can be padded with zeros using various methods:
n = 4 print(f'{n:03}') # Output: 004
n = 4 print('%03d' % n) # Output: 004
n = 4 print(format(n, '03')) # Output: 004
n = 4 print('{0:03d}'.format(n)) # Output: 004
n = 4 print('{foo:03d}'.format(foo=n)) # Output: 004
n = 4 print('{:03d}'.format(n)) # Output: 004
For more information on string formatting, refer to the official Python documentation.
The above is the detailed content of How to Pad Strings and Numbers with Zeros in Python?. For more information, please follow other related articles on the PHP Chinese website!