Python string zfill() - Add (Fill) zero letters to a string

US FIPS codes have five digits and some four-digit numbers start with 0 like 05001 (Arkansas). 05001 starts with 0. So how can we get 05001 from 5001 in Python? The simple way is to use the zfill() that fills 0 in a string.

a = 'ABC'

b = a.zfill(7)

print(b)  # 0000ABC

The parameter is a new length. The length of the original string is 3 so the zfill() fills zero in the leading 4 (= 7 - 3) times.


a = 'ABC'

print(a.zfill(1))  # ABC
print(a.zfill(2))  # ABC
print(a.zfill(3))  # ABC
print(a.zfill(4))  # 0ABC
print(a.zfill(5))  # 00ABC
print(a.zfill(6))  # 000ABC
print(a.zfill(7))  # 0000ABC
print(a.zfill(8))  # 00000ABC

If the parameter is smaller than the length of the old string, the method doesn't fill any zeros.


Powered by Markdown