Home  >  Article  >  Backend Development  >  How to pad 0s into a numeric string to ensure uniform length

How to pad 0s into a numeric string to ensure uniform length

anonymity
anonymityOriginal
2019-05-25 10:51:492650browse

Is there any way to fill the left side of a string with 0s so that it has a specific length?

How to pad 0s into a numeric string to ensure uniform length

String

n = '5'
print n.zfill(3)
005

t = 'test'
print(t.rjust(10, '0'))

Number

n = 4
print('%03d' % n)
004

format

print(format(4, '03')) # python >= 2.6
 
print("{0:03d}".format(4))  # python >= 2.6
 
print("{0:03d}".format(4))  # python 3

: The padding character after the sign can only be one character. If not specified, it will be filled with spaces by default, followed by the guaranteed number of padding digits

b, d, o , x are binary, decimal, octal, and hexadecimal respectively.

Precision is often used together with type f, and the number can also be used as the thousands separator for amounts.

The above is the detailed content of How to pad 0s into a numeric string to ensure uniform length. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn