How to Pad a Numeric String with Zeros to the Left in Python
Created
Modified
Using zfill Method
The str.zfill(width)
method returns a copy of the string left filled with ASCII '0' digits to make a string of length width. For example,
#!/usr/bin/python3
# s = str(n)
s = '6'
print(s.zfill(4))
# leading sign prefix
s = '-6'
print(s.zfill(4))
0006 -006
Using rjust Method
The str.rjust(width[, fillchar])
method returns the string right justified in a string of length width. For example,
#!/usr/bin/python3
s = '6'
print(s.rjust(4, '0'))
# leading sign prefix
s = '-6'
print(s.rjust(4, '0'))
0006 00-6
Using String Formatting and f-strings
You can use string formatting or f-strings to pad a numeric string with zeros to the left, it really simple. For example,
#!/usr/bin/python3
n = -6
print('%04d' % n)
print(format(n, '04'))
print('{0:04d}'.format(n))
print('{:04d}'.format(n))
# f-strings
# python >= 3.6
print(f'{n:04}')
print(f'{n:0>4}')
-006 -006 -006 -006 -006 00-6