问题:显示数字的前导零

鉴于:

a = 1
b = 10
c = 100

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

这是我期望的输出:

01
10
100

Given:

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

This is the output I’m expecting:

01
10
100

回答 0

在Python 2(和Python 3)中,您可以执行以下操作:

print "%02d" % (1,)

基本上就像printfsprintf(请参阅docs)。


对于Python 3. +,也可以通过以下方式实现相同的行为format

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

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

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

In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

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

For Python 3.6+ the same behavior can be achieved with f-strings:

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

回答 1

您可以使用str.zfill

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

印刷品:

01
10
100

You can use str.zfill:

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

prints:

01
10
100

回答 2

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

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

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

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

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

In Python 2.6+ and 3.0+, you would use the format() string method:

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.


回答 3

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

印刷品:

01
10
100
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

prints:

01
10
100

回答 4

或这个:

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

Or this:

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


回答 5

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

In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:

f'{val:02}'

which prints the variable with name val with a fill value of 0 and a width of 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.


回答 6

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

结果是:

01
10
100

在文档中阅读有关使用%格式化字符串的更多信息

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.


回答 7

使用Python的方式:

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

The Pythonic way to do this:

str(number).rjust(string_width, fill_char)

This way, the original string is returned unchanged if its length is greater than string_width. Example:

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

Results:

01
10
100

回答 8

或其他解决方案。

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

Or another solution.

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

回答 9

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

例如:

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

Use a format string – http://docs.python.org/lib/typesseq-strings.html

For example:

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

回答 10

这是我的方法:

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

基本上,zfill接受要添加的前导零的数量,因此很容易将最大的数字转换为字符串并获取长度,如下所示:

Python 3.6.5(默认,2018年5月11日,04:00:52) 
Linux上的[GCC 8.1.0]
键入“帮助”,“版权”,“信用”或“许可证”以获取更多信息。
>>>总计= 100
>>>打印(str(1).zfill(len(str(total))))
001
>>>总计= 1000
>>>打印(str(1).zfill(len(str(total))))
0001
>>>总计= 10000
>>>打印(str(1).zfill(len(str(total))))
00001
>>> 

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:

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
>>> 

回答 11

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

回答 12

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

import numpy as np

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

这将打印恒定长度的8,并用领先的填充0

00000001
00000124
00013566

You can do this with 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.

00000001
00000124
00013566

回答 13

采用:

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

或与math模块:

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

Use:

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

Or with the math module:

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

回答 14

df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))

5是总位数。

我使用了以下链接:http : //www.datasciencemadesimple.com/add-leading-preceding-zeros-python/

df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))

The 5 is the number of total digits.

I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/


回答 15

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

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

If dealing with numbers that are either one or two digits:

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。