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.py90 chars7 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.
gistlibby LogSnag