ChatGPT解决这个技术问题 Extra ChatGPT

显示带前导零的数字

如何为所有少于两位数的数字显示前导零?

1    →  01
10   →  10
100  →  100

F
Flimm

在 Python 2(和 Python 3)中,您可以:

number = 1
print("%02d" % (number,))

% 基本上类似于 printfsprintf(参见 docs)。

对于 Python 3.+,使用 format 也可以实现相同的行为:

number = 1
print("{:02d}".format(number))

对于 Python 3.6+,使用 f-strings 可以实现相同的行为:

number = 1
print(f"{number:02d}")

示例:为 5 位邮政编码打印 "%05d" % result['postalCode']。
x = "%02d.txt" % i 引发 TypeError(无法连接 'str' 和 'int' 对象),但 x = "%02d.txt" % (i,) 不会。有趣的。我想知道这是在哪里记录的
@theta 在 2.7.6 中,我没有收到错误消息。也许这是他们已经修复的特定 Python 版本中的错误?
也许。在 2.7.6 中,如果格式值不是元组(至少对于本示例),也不例外。看看我发表评论的日期,我想我当时正在运行 2.7.3,当时我不知道在使用 % 字符串格式化程序时将单个变量放在一个元组中可以让你安全。
详细地说,docs 在这里解释:“当没有给出明确的对齐方式时,在宽度字段前加上零 ('0') 字符可以为数字类型启用符号感知零填充。这相当于填充字符'0' 的对齐类型为 '='。”
N
Neuron

您可以使用 str.zfill

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

印刷:

01
10
100

我喜欢这个解决方案,因为它不仅在输出数字时有帮助,而且在您需要将其分配给变量时也有帮助......例如 x = str(datetime.date.today().month).zfill(2) 将返回x 为 2 月的“02”。
这应该是正确的答案,因为 "{1:02d}" 不能有变量来代替 2(就像您正在创建动态函数一样)。
@JoshuaVarghese 它可以有变量:"{0:0{1}}"。传递任意数量的零作为第二个参数。
楼上的回答太好了!但是这个是目前最好的。
此方法也适用于在浮点数前添加零。
p
phoenix

在 Python 2.6+ 和 3.0+ 中,您将使用 format() 字符串方法:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

或使用内置(对于单个数字):

print(format(i, '02d'))

有关新的格式化函数,请参阅 PEP-3101 文档。


也适用于 Python 2.7.5。如果您不想使用命名参数,也可以使用 '{:02d}'.format(1)。
在 2.7.2 中工作正常,浮点 "{0:04.0f}".format(1.1) 给出 0001(:04 = 至少 4 个字符,在这种情况下前导 0,.0f = 没有小数的浮点) .我知道 % 格式,但想修改现有的 .format 语句而不重写整个内容。谢谢!
N
Neuron
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

印刷:

01
10
100

这样,您可以在字符串中多次重复参数:One zero:{0:02}, two zeros: {0:03}, ninezeros: {0:010}'.format(6)
仅与 Python 3 兼容。如果使用 Python 2.7,请执行 print '{:02}'.format(1)
N
Neuron

在 Python >= 3.6 中,您可以使用引入的新 f 字符串简洁地做到这一点:

f'{val:02}'

它打印名称为 val 的变量,其 fill 值为 0width2

对于您的具体示例,您可以在循环中很好地执行此操作:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

打印:

01 
10
100

有关 f 字符串的更多信息,请查看 PEP 498 介绍它们的位置。


a
ajd

或这个:

print '{0:02d}'.format(1)


N
Neuron
x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果是:

01
10
100

阅读文档中的 more information about string formatting using %


文档示例很糟糕。他们使用前导零样本进行映射,因此除非您已经知道它是如何工作的,否则很难知道哪个是哪个。实际上,这就是把我带到这里的原因。
N
Neuron

执行此操作的 Pythonic 方式:

str(number).rjust(string_width, fill_char)

这样,如果其长度大于 string_width,则原始字符串将原样返回。例子:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

结果:

01
10
100

K
Kenly

或者另一种解决方案。

"{:0>2}".format(number)

这将是 Python 方式,尽管为了清楚起见我会包含参数 - "{0:0>2}".format(number),如果有人想要 nLeadingZeros,他们应该注意他们也可以这样做:"{0:0>{1}}".format(number, nLeadingZeros + 1)
N
Nicolas Gervais

您可以使用 f 字符串来执行此操作。

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

这将打印 8 的恒定长度,并用前导 0 填充其余部分。

00000001
00000124
00013566

P
Peter Mortensen

我就是这样做的:

str(1).zfill(len(str(total)))

基本上 zfill 取你要添加的前导零的数量,所以很容易取最大的数字,把它变成一个字符串并得到长度,像这样:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>>

这与Datageek's answer不矛盾吗?
A
Airsource Ltd

使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html

例如:

python -c 'print "%(num)02d" % {"num":5}'

n
nvd
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

P
Peter Mortensen

利用:

'00'[len(str(i)):] + str(i)

或使用 math 模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

h
handle

所有这些都创建了字符串“01”:

>python -m timeit "'{:02d}'.format(1)"
1000000 loops, best of 5: 357 nsec per loop

>python -m timeit "'{0:0{1}d}'.format(1,2)"
500000 loops, best of 5: 607 nsec per loop

>python -m timeit "f'{1:02d}'"
1000000 loops, best of 5: 281 nsec per loop

>python -m timeit "f'{1:0{2}d}'"
500000 loops, best of 5: 423 nsec per loop

>python -m timeit "str(1).zfill(2)"
1000000 loops, best of 5: 271 nsec per loop

>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32

Z
Zahid Riaz

这将是 Python 的方式,尽管为了清楚起见我会包含参数 - “{0:0>2}”.format(number),如果有人想要 nLeadingZeros,他们应该注意他们也可以这样做:“{0:0> {1}}".format(数字,nLeadingZeros + 1)


S
Stuart Demmer

你也可以这样做:

'{:0>2}'.format(1)

这将返回一个字符串。


K
Knowbody

如果处理一位或两位数的数字:

'0'+str(number)[-2:]'0{0}'.format(number)[-2:]