[英]Display number with leading zeros
How do I display a leading zero for all numbers with less than two digits?如何为所有少于两位数的数字显示前导零?
1 → 01
10 → 10
100 → 100
In Python 2 (and Python 3) you can do:在 Python 2(和 Python 3)中,您可以:
number = 1
print("%02d" % (number,))
Basically % is like printf
or sprintf
(see docs ).基本上%就像
printf
或sprintf
(请参阅文档)。
For Python 3.+, the same behavior can also be achieved with format
:对于 Python 3.+,同样的行为也可以通过
format
实现:
number = 1
print("{:02d}".format(number))
For Python 3.6+ the same behavior can be achieved with f-strings :对于 Python 3.6+,可以使用f-strings实现相同的行为:
number = 1
print(f"{number:02d}")
In Python 2.6+ and 3.0+, you would use the format()
string method:在 Python 2.6+ 和 3.0+ 中,您将使用
format()
字符串方法:
for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
or using the built-in (for a single number):或使用内置(对于单个数字):
print(format(i, '02d'))
See the PEP-3101 documentation for the new formatting functions.有关新的格式化功能,请参阅PEP-3101文档。
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
prints:印刷:
01
10
100
In Python >= 3.6 , you can do this succinctly with the new f-strings that were introduced by using:在Python >= 3.6中,您可以使用引入的新 f 字符串简洁地做到这一点:
f'{val:02}'
which prints the variable with name val
with a fill
value of 0
and a width
of 2
.它打印名为
val
的变量, fill
值为0
, width
为2
。
For your specific example you can do this nicely in a loop:对于您的具体示例,您可以在循环中很好地执行此操作:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
which prints:打印:
01
10
100
For more information on f-strings, take a look at PEP 498 where they were introduced.有关 f 字符串的更多信息,请查看引入它们的PEP 498 。
或这个:
print '{0:02d}'.format(1)
x = [1, 10, 100]
for i in x:
print '%02d' % i
results in:结果是:
01
10
100
Read more information about string formatting using % in the documentation.在文档中阅读有关使用 % 进行字符串格式化的更多信息。
The Pythonic way to do this:执行此操作的 Pythonic 方式:
str(number).rjust(string_width, fill_char)
This way, the original string is returned unchanged if its length is greater than string_width.这样,如果其长度大于 string_width,则原始字符串将原样返回。 Example:
例子:
a = [1, 10, 100]
for num in a:
print str(num).rjust(2, '0')
Results:结果:
01
10
100
或者另一种解决方案。
"{:0>2}".format(number)
You can do this with f strings .你可以用f strings来做到这一点。
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
This will print constant length of 8, and pad the rest with leading 0
.这将打印 8 的恒定长度,并用前导
0
填充其余部分。
00000001
00000124
00013566
This is how I do it:我就是这样做的:
str(1).zfill(len(str(total)))
Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:基本上 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 >>>
Use a format string - http://docs.python.org/lib/typesseq-strings.html使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html
For example:例如:
python -c 'print "%(num)02d" % {"num":5}'
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
Use:利用:
'00'[len(str(i)):] + str(i)
Or with the math
module:或者使用
math
模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
All of these create the string "01":所有这些都创建了字符串“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)
s=1
s="%02d"%s
print(s)
the result will be 01 结果将是01
You could also do:你也可以这样做:
'{:0>2}'.format(1)
which will return a string.这将返回一个字符串。
!/usr/bin/env python3 !/ usr / bin / env python3
Copyright 2009-2017 BHG http://bw.org/ 版权所有2009-2017 BHG http://bw.org/
x = 5
while (x <= 15):
a = str("{:04}".format(x))
print(a)
x = x + 1;
df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))
The 5 is the number of total digits. 5 是总位数。
I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/我使用了这个链接: http : //www.datasciencemadesimple.com/add-leading-preceding-zeros-python/
If dealing with numbers that are either one or two digits:如果处理一位或两位数的数字:
'0'+str(number)[-2:]
or '0{0}'.format(number)[-2:]
'0'+str(number)[-2:]
或'0{0}'.format(number)[-2:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.