Explain Codes LogoExplain Codes Logo

How do I pad a string with zeroes?

python
prompt-engineering
functions
dataframe
Anton ShumikhinbyAnton Shumikhin·Nov 10, 2024
TLDR

If you're in a rush, Python has got you covered with the str.zfill() method:

# Super express zero delivery! "42".zfill(5) # '00042'

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:

# Python be like: "It's perfect the way it is!" "12345".zfill(5) # '12345'

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:

n = 42 # 42 special characters in ASCII... Coincidence? I think not! f"{n:05}" # '00042'

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:

# It's good to put names to faces. Or numbers... "{number:05d}".format(number=42) # '00042'

Or with % formatting (even older, but still gold):

# % is basically the history teacher of Python. "%05d" % 42 # '00042'

.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:

# A "test" that passes before it begins! "test".rjust(8, '0') # '0000test' "test".ljust(8, '0') # 'test0000'

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:

# Names, the key to destiny. "{filename:020}".format(filename="report") # '00000000000000report'

Express inline formatting

Sometimes, you need to pad right in the middle of the action:

# The day the date stood still. f"Date: {year:04}-{month:02}-{day:02}" # 'Date: 2023-03-14'

Left or right? It's your right!

Choose your padding side according to your needs:

# Left or Right? Only the oracle knows. left_padded = "42".rjust(5, '0') # '00042' right_padded = "42".ljust(5, '0') # '42000'

Visual impact and data parsing might tip the scale!

Variable length? Loop it!

Got a variable-length list? Just use a loop:

# The circle of life, for numbers. numbers = [5, 50, 500] padded = [f"{n:03}" for n in numbers] # ['005', '050', '500']

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:

# Who ordered a string of numbers? "2".zfill(3) # '002' "10".zfill(3) # '010'

Wait, are you a number or a string?

Do check and convert non-string types before padding:

# Just making sure... str(42).zfill(5) # '00042'

Python won't be mad with wrong padding width, but might give you a funny look:

# Maybe you counted on your fingers? "42".zfill(2) # '42'

Mixin' it up

Get fancy with mixed formatters for eclectic padding parties:

# Time for a formatted party! f"{hour:02}:{minute:02}:{second:02}" # 'Hours:Minutes:Seconds with padding'

Consistency in padding enhances both data readability and your karma.