如何为所有少于两位数的数字显示前导零?
1 → 01
10 → 10
100 → 100
您可以使用 str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
印刷:
01
10
100
"{1:02d}"
不能有变量来代替 2
(就像您正在创建动态函数一样)。
"{0:0{1}}"
。传递任意数量的零作为第二个参数。
在 Python 2.6+ 和 3.0+ 中,您将使用 format()
字符串方法:
for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
或使用内置(对于单个数字):
print(format(i, '02d'))
有关新的格式化函数,请参阅 PEP-3101 文档。
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)
print '{:02}'.format(1)
或这个:
print '{0:02d}'.format(1)
x = [1, 10, 100]
for i in x:
print '%02d' % i
结果是:
01
10
100
阅读文档中的 more information about string formatting using %。
执行此操作的 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
或者另一种解决方案。
"{:0>2}".format(number)
"{0:0>2}".format(number)
,如果有人想要 nLeadingZeros,他们应该注意他们也可以这样做:"{0:0>{1}}".format(number, nLeadingZeros + 1)
您可以使用 f 字符串来执行此操作。
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
这将打印 8 的恒定长度,并用前导 0
填充其余部分。
00000001
00000124
00013566
我就是这样做的:
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 >>>
使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html
例如:
python -c 'print "%(num)02d" % {"num":5}'
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
利用:
'00'[len(str(i)):] + str(i)
或使用 math
模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
所有这些都创建了字符串“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
这将是 Python 的方式,尽管为了清楚起见我会包含参数 - “{0:0>2}”.format(number),如果有人想要 nLeadingZeros,他们应该注意他们也可以这样做:“{0:0> {1}}".format(数字,nLeadingZeros + 1)
你也可以这样做:
'{:0>2}'.format(1)
这将返回一个字符串。
如果处理一位或两位数的数字:
'0'+str(number)[-2:]
或 '0{0}'.format(number)[-2:]
不定期副业成功案例分享
x = "%02d.txt" % i
引发 TypeError(无法连接 'str' 和 'int' 对象),但x = "%02d.txt" % (i,)
不会。有趣的。我想知道这是在哪里记录的%
字符串格式化程序时将单个变量放在一个元组中可以让你安全。