How To Pad a String in Python
Convert 9 to 09
Does it bother you when your numbers don’t line up? Does your project require a set character length regardless of input? If the answer is yes, then you most likely need to pad your string—or number—values.
In Python, this task is made simple with the .zfill() Python string method.
What Is zfill()?
The .zfill() method is part of the string class, meaning that it can only be performed on a string value.# will work
result = "9".zfill(2)# won't work
result = 9.zfill(2)
The method requires a single parameter, the maximum length of the string, if padded.
There are three possibilities here: The fill length is less than, equal to, or greater than the length of the original string. Let’s see what happens in each case.a = "8"
b = "80"
c = "800"print(a.zfill(2),b.zfill(2),c.zfill(2)) # 08 80 800
As you can see, when the fill length is greater than the original string, 0s will be added to the left of the string until it meets the fill length. When the two are equal, the string is expectedly unaltered. When the fill length is less, the original string remains unaltered — it’s not shortened to match the fill length.
So what happens when our variable isn’t a string?
In these scenarios, the answer is as simple as converting our value to a string using the str() function.id = 12345
id = str(id).zfill(8)
print(id) # 00012345
Conclusion
Never worry about awkward loops and manually padding string values again. Use the .zfill() method and reliably left pad your strings.