如何在 Python 3 中用前导零填充字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39402795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:13:13  来源:igfitidea点击:

How to pad a string with leading zeros in Python 3

pythonpython-3.xmathrounding

提问by Gabby Freeland

I'm trying to make length = 001in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1). How would I stop this happening without having to cast lengthto a string before printing it out?

我正在尝试length = 001在 Python 3 中制作,但是每当我尝试将其打印出来时,它都会截断没有前导零 ( length = 1)的值。我将如何阻止这种情况发生而不必length在打印出来之前转换为字符串?

回答by nyedidikeke

Make use of the zfill()helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.xand Python 3.x.

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

Sample usage:

示例用法:

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

Description:

描述:

When applied to a value, zfill()returns a value left-padded with zeros when the length of the initial stringvalue less than that of the applied widthvalue, otherwise, the initial stringvalue as is.

当应用于一个值时,zfill()当初始字符串值的长度小于应用的宽度值的长度时,返回一个用零填充的值,否则返回初始字符串值。

Syntax:

句法:

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

回答by PhE

Since python 3.6 you can use fstring :

从 python 3.6 开始,您可以使用 fstring :

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

回答by Blckknght

Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.

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

To pad with zeros to a minimum of three characters, try:

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

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

回答by Anatol

There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:

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

print(f"{1:03}")

回答by wydadman

I suggest this ugly method but it works:

我建议使用这种丑陋的方法,但它有效:

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

I came here to find a lighter solution than this one!

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