ash*_*her 819 python integer string-formatting
鉴于:
a = 1
b = 10
c = 100
Run Code Online (Sandbox Code Playgroud)
如何为少于两位数的所有数字显示前导零?
那是,
01
10
100
Run Code Online (Sandbox Code Playgroud)
Jac*_* M. 912
在Python 2中,您可以:
print "%02d" % (1,)
Run Code Online (Sandbox Code Playgroud)
基本上%就像printf或sprintf.
对于Python 3 +,可以通过以下方式实现相同的行为:
print("{:02d}".format(1))
Run Code Online (Sandbox Code Playgroud)
对于Python 3.6+,使用f-strings可以实现相同的行为:
print(f"{1:02d}")
Run Code Online (Sandbox Code Playgroud)
Dat*_*eek 863
你可以使用str.zfill:
print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
Run Code Online (Sandbox Code Playgroud)
打印:
01
10
100
Run Code Online (Sandbox Code Playgroud)
Ber*_*Ber 358
在Python 2.6+和3.0+中,您将使用format()字符串方法:
for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
Run Code Online (Sandbox Code Playgroud)
或使用内置(对于单个数字):
print(format(i, '02d'))
Run Code Online (Sandbox Code Playgroud)
有关新的格式化功能,请参阅PEP-3101文档.
Kre*_*mir 125
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
Run Code Online (Sandbox Code Playgroud)
打印:
01
10
100
Run Code Online (Sandbox Code Playgroud)
Jim*_*ard 65
在Python> = 3.6中,您可以使用以下引入的新f字符串简洁地执行此操作:
f'{val:02}'
Run Code Online (Sandbox Code Playgroud)
它打印用名称的变量val具有fill的值0和width的2.
对于您的具体示例,您可以在循环中很好地执行此操作:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
Run Code Online (Sandbox Code Playgroud)
打印:
01
10
100
Run Code Online (Sandbox Code Playgroud)
有关f-strings的更多信息,请参阅PEP 498.
nos*_*klo 53
x = [1, 10, 100]
for i in x:
print '%02d' % i
Run Code Online (Sandbox Code Playgroud)
结果是:
01
10
100
Run Code Online (Sandbox Code Playgroud)
在文档中使用%阅读有关字符串格式的更多信息.
ZuL*_*uLu 47
Pythonic的方法:
str(number).rjust(string_width, fill_char)
Run Code Online (Sandbox Code Playgroud)
这样,如果原始字符串的长度大于string_width,则返回原始字符串.例:
a = [1, 10, 100]
for num in a:
print str(num).rjust(2, '0')
Run Code Online (Sandbox Code Playgroud)
结果:
01
10
100
Run Code Online (Sandbox Code Playgroud)
Win*_*lly 32
或另一种解决方案
"{:0>2}".format(number)
Run Code Online (Sandbox Code Playgroud)
这就是我的做法:
str(1).zfill(len(str(total)))
Run Code Online (Sandbox Code Playgroud)
基本上 zfill 需要您要添加的前导零的数量,因此很容易取最大的数字,将其转换为字符串并获取长度,如下所示:
Python 3.6.5(默认,2018 年 5 月 11 日,04:00:52) [GCC 8.1.0] 在 Linux 上 输入“帮助”、“版权”、“信用”或“许可”以获取更多信息。 >>> 总数 = 100 >>> 打印(str(1).zfill(len(str(total)))) 001 >>> 总数 = 1000 >>> 打印(str(1).zfill(len(str(total)))) 0001 >>> 总计 = 10000 >>> 打印(str(1).zfill(len(str(total)))) 00001 >>>
你可以用f strings来做到这一点。
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
Run Code Online (Sandbox Code Playgroud)
这将打印 8 的恒定长度,并用前导填充其余部分0。
00000001
00000124
00013566
Run Code Online (Sandbox Code Playgroud)
使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html
例如:
python -c 'print "%(num)02d" % {"num":5}'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
707916 次 |
| 最近记录: |