How do I pad a string with zeroes?
If you're in a rush, Python has got you covered with the str.zfill()
method:
This method adds leading zeroes to a string until it reaches a specified length. If you try to pad less than the string's length, Python just says, "No worries, fam!" and leaves it be:
More padding, more options
Sure, zfill()
is quick and sweet. But Python isn't a one-trick snake! Let me introduce some alternate padding options:
Padding with f-strings (Python 3.6+)
The f-string can also pad your lonely string:
This method is both concise and readable, and even allows for in-string expressions. Yes, you heard that right!
Padding with .format
and %
Ever heard of the .format()
method? It's a bit old school, but it still does the trick:
Or with %
formatting (even older, but still gold):
.format()
is flexible like a good yoga teacher, %
is like your grandma: familiar, comforting, but a bit old-fashioned.
Padding with rjust
and ljust
What if your string doesn't identify as a number? No problemo! Meet rjust
and ljust
:
These methods are for those who want extra control on alignment, or for those little rebels who want to pad to the right!
Padding: Redux
Named placeholders
Need to make your padding intentions clear? Look no further than named placeholders:
Express inline formatting
Sometimes, you need to pad right in the middle of the action:
Left or right? It's your right!
Choose your padding side according to your needs:
Visual impact and data parsing might tip the scale!
Variable length? Loop it!
Got a variable-length list? Just use a loop:
This way, uniformity is enforced on dynamic data, making everything zen.
Digging deeper
Organised chaos
Zero-padding helps maintain numerical order even in a string datatype:
Wait, are you a number or a string?
Do check and convert non-string types before padding:
Python won't be mad with wrong padding width, but might give you a funny look:
Mixin' it up
Get fancy with mixed formatters for eclectic padding parties:
Consistency in padding enhances both data readability and your karma.
Was this article helpful?