显示带前导零的数字

发布于 2024-07-06 07:35:51 字数 124 浏览 7 评论 0 原文

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

1    →  01
10   →  10
100  →  100

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

1    →  01
10   →  10
100  →  100

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

水中月 2024-07-13 07:35:51

在Python 2(和Python 3)中,你可以这样做:

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

基本上 % 就像 printfsprintf (参见 文档)。


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

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

对于 Python 3.6+,可以使用 f 字符串

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

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

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

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


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

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

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

number = 1
print(f"{number:02d}")
葬﹪忆之殇 2024-07-13 07:35:51

您可以使用 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
扮仙女 2024-07-13 07:35:51

在 Python 2.6+ 和 3.0+ 中,您可以使用 format()< /code> 字符串方法:

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.

浸婚纱 2024-07-13 07:35:51
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
时光病人 2024-07-13 07:35:51

Python >= 3.6 中,您可以使用引入的新 f 字符串来简洁地执行此操作:

f'{val:02}'

使用 val 的变量="https://docs.python.org/3/library/string.html#grammar-token-fill" rel="noreferrer">填充0 宽度< /a> 2

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

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.

九公里浅绿 2024-07-13 07:35:51

或者这样:

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

Or this:

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

梦旅人picnic 2024-07-13 07:35:51
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.

泪是无色的血 2024-07-13 07:35:51

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

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
不羁少年 2024-07-13 07:35:51

或者另一种解决方案。

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

Or another solution.

"{:0>2}".format(number)
习ぎ惯性依靠 2024-07-13 07:35:51

它内置于 python 中,具有字符串格式

f'{number:02d}'

Its built into python with string formatting

f'{number:02d}'
太阳男子 2024-07-13 07:35:51

您可以使用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
鞋纸虽美,但不合脚ㄋ〞 2024-07-13 07:35:51

我就是这样做的:

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

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
>>> 
清醇 2024-07-13 07:35:51

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

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}'
江心雾 2024-07-13 07:35:51

您也可以这样做:

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

这将返回一个字符串。

You could also do:

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

which will return a string.

玩心态 2024-07-13 07:35:51
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
哀由 2024-07-13 07:35:51

使用:

'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)
风为裳 2024-07-13 07:35:51

所有这些都会创建字符串“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

All of these create the string "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
以可爱出名 2024-07-13 07:35:51

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

This would be the Python way, although I would include the parameter for clarity - "{0:0>2}".format(number), if someone will wants nLeadingZeros they should note they can also do:"{0:0>{1}}".format(number, nLeadingZeros + 1)

好听的两个字的网名 2024-07-13 07:35:51

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

'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:]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文