如何在数字字符串的左边加上零,使字符串具有特定的长度?
当前回答
快速定时比较:
setup = '''
from random import randint
def test_1():
num = randint(0,1000000)
return str(num).zfill(7)
def test_2():
num = randint(0,1000000)
return format(num, '07')
def test_3():
num = randint(0,1000000)
return '{0:07d}'.format(num)
def test_4():
num = randint(0,1000000)
return format(num, '07d')
def test_5():
num = randint(0,1000000)
return '{:07d}'.format(num)
def test_6():
num = randint(0,1000000)
return '{x:07d}'.format(x=num)
def test_7():
num = randint(0,1000000)
return str(num).rjust(7, '0')
'''
import timeit
print timeit.Timer("test_1()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_2()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_3()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_4()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_5()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_6()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_7()", setup=setup).repeat(3, 900000)
> [2.281613943830961, 2.2719342631547077, 2.261691106209631]
> [2.311480238815406, 2.318420542148333, 2.3552384305184493]
> [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]
> [2.312442972404032, 2.318053102249902, 2.3054072168069872]
> [2.3482314132374853, 2.3403386400002475, 2.330108825844775]
> [2.424549090688892, 2.4346475296851438, 2.429691196530058]
> [2.3259756401716487, 2.333549212826732, 2.32049893822186]
我做了不同重复的不同测试。差异不大,但在所有测试中,zfill解决方案都是最快的。
其他回答
您也可以重复“0”,将其前置到str(n)并获得最右侧的宽度切片。又快又脏的小表情。
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
另一种方法是使用列表理解和长度检查条件。下面是一个演示:
# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]
# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']
也可以:
h = 2
m = 7
s = 3
print("%02d:%02d:%02d" % (h, m, s))
因此输出将为:“02:07:03”
使用Python>=3.6时,最干净的方法是将f-string与字符串格式一起使用:
>>> s = f"{1:08}" # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}" # inline with str
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}" # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}" # str variable
>>> s
'00000001'
我更喜欢使用int格式,因为只有这样符号才能正确处理:
>>> f"{-1:08}"
'-0000001'
>>> f"{1:+08}"
'+0000001'
>>> f"{'-1':0>8}"
'000000-1'
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
有关所有令人兴奋的详细信息,请参阅打印文档!
Python 3.x更新(7.5年后)
最后一行现在应该是:
print("%0*d" % (width, x))
即print()现在是一个函数,而不是一个语句。注意,我仍然更喜欢Old School printf()风格,因为IMNSHO,它读起来更好,而且,嗯,我从1980年1月起就一直使用这种符号。某物老狗。。一些东西。。。新技巧。