Home > Backend Development > Python Tutorial > 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
Release: 2019-05-25 10:51:49
Original
2651 people have browsed it

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'))
Copy after login

Number

n = 4
print('%03d' % n)
004
Copy after login

format

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template