如何在 Python 3 中用前导零填充字符串[重复]

问题描述 投票:0回答:5

我试图在Python 3中制作

length = 001
,但每当我尝试打印它时,它都会截断该值,不带前导零(
length = 1
)。我该如何阻止这种情况发生,而无需在打印之前将
length
转换为字符串?

python python-3.x math rounding
5个回答
206
投票

利用

zfill()
辅助方法向左填充任何字符串、整数或浮点值为零;它对 Python 2.xPython 3.x 都有效。

需要注意的是,Python 2 不再受支持

使用示例:

print(str(1).zfill(3))
# Expected output: 001

描述:

应用于值时,当初始

string
值的长度小于所应用的 width 值的长度时,zfill() 返回左填充零的值,否则,按原样初始 string 值。

语法:

str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.

166
投票

从 python 3.6 开始你可以使用 f-string :

>>> length = "1"
>>> print(f'length = {length:03}')
length = 100
>>> print(f'length = {length:>03}')
length = 001

48
投票

有很多方法可以实现这一点,但在我看来,Python 3.6+ 中最简单的方法是:

print(f"{1:03}")

13
投票

Python 整数没有固有的长度或有效位数。如果您希望它们以特定方式打印,则需要将它们转换为字符串。您可以通过多种方法来指定填充字符和最小长度等内容。

要用零填充至少三个字符,请尝试:

length = 1
print(format(length, '03'))

-8
投票

我建议这个丑陋的方法,但它有效:

length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)

我来这里是为了找到比这个更轻松的解决方案!

© www.soinside.com 2019 - 2024. All rights reserved.