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


当前回答

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

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

其他回答

使用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'

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

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

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

也可以:

 h = 2
 m = 7
 s = 3
 print("%02d:%02d:%02d" % (h, m, s))

因此输出将为:“02:07:03”

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

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

str(n).zfill(width)将处理字符串、int、浮点。。。并且兼容Python 2.x和3.x:

>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'