Pad Strings with Zeros
This article addresses the query of how to add zero padding to the left of a numerical string, ensuring a specific length for the string. Two primary methods exist for achieving this: padding strings and padding numbers.
Padding Strings
To pad strings, use the zfill() function:
n = '4' print(n.zfill(3)) # Outputs "004"
Padding Numbers
For numbers, there are several options:
n = 4 print(f'{n:03}') # Recommended, Outputs "004"
print('%03d' % n) # Outputs "004"
print(format(n, '03')) # Outputs "004" print('{0:03d}'.format(n)) # Outputs "004" print('{foo:03d}'.format(foo=n)) # Outputs "004"
print('{:03d}'.format(n)) # Outputs "004"
Refer to the official String formatting documentation for further information.
The above is the detailed content of How Can I Left-Pad a String or Number with Zeros in Python?. For more information, please follow other related articles on the PHP Chinese website!