python – How to pad zeroes to a string?

python – How to pad zeroes to a string?

Strings:

>>> n = 4
>>> print(n.zfill(3))
004

And for numbers:

>>> n = 4
>>> print(f{n:03}) # Preferred method, python >= 3.6
004
>>> print(%03d % n)
004
>>> print(format(n, 03)) # python >= 2.6
004
>>> print({0:03d}.format(n))  # python >= 2.6 + python 3
004
>>> print({foo:03d}.format(foo=n))  # python >= 2.6 + python 3
004
>>> print({:03d}.format(n))  # python >= 2.7 + python3
004

String formatting documentation.

Just use the rjust method of the string object.

This example will make a string of 10 characters long, padding as necessary.

>>> t = test
>>> t.rjust(10, 0)
>>> 000000test

python – How to pad zeroes to a string?

Besides zfill, you can use general string formatting:

print(f{number:05d}) # (since Python 3.6), or
print({:05d}.format(number)) # or
print({0:05d}.format(number)) # or (explicit 0th positional arg. selection)
print({n:05d}.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, 05d))

Documentation for string formatting and f-strings.

Leave a Reply

Your email address will not be published. Required fields are marked *