如何在数字字符串的左边加上零,使字符串具有特定的长度?
当前回答
使用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'
其他回答
也可以:
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'
另一种方法是使用列表理解和长度检查条件。下面是一个演示:
# 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']
您也可以重复“0”,将其前置到str(n)并获得最右侧的宽度切片。又快又脏的小表情。
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
只需使用字符串对象的rjust方法。
此示例创建一个10个字符长度的字符串,根据需要进行填充:
>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'