如何在数字字符串的左边加上零,使字符串具有特定的长度?


当前回答

只需使用字符串对象的rjust方法。

此示例创建一个10个字符长度的字符串,根据需要进行填充:

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'

其他回答

对于数字:

i = 12
print(f"{i:05d}")

输出

00012
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月起就一直使用这种符号。某物老狗。。一些东西。。。新技巧。

我添加了如何使用f-string中字符串长度的int,因为它似乎没有被覆盖:

>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'

另一种方法是使用列表理解和长度检查条件。下面是一个演示:

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