zero pad in python

To zero pad a string in Python, you can use the built-in function str.zfill(). This function takes an argument specifying the desired width, and pads the string with zeros on the left side to reach that width.

Here's an example:

main.py
number = 42
width = 5

padded = str(number).zfill(width)

print(padded)  # prints "00042"
90 chars
7 lines

In this example, number is 42, and width is 5. The str() function is called to convert number to a string, and zfill() is called on that string to zero-pad it to the desired width.

Note that you can also pad with other characters besides zero. For example, str.rjust() can be used to right-justify a string and pad with spaces or other characters.

related categories

gistlibby LogSnag