恢复Python列表中丢失的前导零



我有一个地理邮政编码列表,其格式为xxxx(一串数字(。

然而,在收集和处理数据的过程中,在邮政编码以'0'开头的情况下,前导零已经丢失。

在这种情况下,我需要恢复领先的'0'

邮政编码要么以xxxx的形式出现,要么在我的列表中以xxxx-xxxx的形式出现。

拥有:

v = ['821-322', '877', '2004-2218', '2022']

期望输出:

['0821-0322', '0877', '2004-2218', '2022']
^    ^       ^

尝试:

for i in range(len(v)):
v[i] = re.sub(pattern, '0' + pattern, v)

然而,我很难理解regex模式,以及如何简单地获得所需的结果
不要求使用re.sub()。任何简单的解决方案都可以。

您应该使用f-string格式!

这里有一句话可以解决你的问题:

>>> v = ['821-322', '877', '2004-2218', '2022']
>>> ["-".join([f'{i:0>4}' for i in x.split("-")]) for x in v]
['0821-0322', '0877', '2004-2218', '2022']

一个更详细的例子是:

v = ['821-322', '877', '2004-2218', '2022']
newv = []
for number in v:
num_holder = []    
# Split the numbers on "-", returns a list of one if no split occurs
for num in number.split("-"):
# Append the formatted string to num_holder
num_holder.append(f'{num:0>4}')
# After each number has been formatted correctly, create a
# new string which is joined together with a "-" once again and append it to newv
newv.append("-".join(num_holder))
print(newv)

你可以在这里阅读更多关于f字符串如何工作的信息;迷你语言";这里的格式化程序使用的

简短的解释是:

f'{num:0>4}'

  • f告诉解释程序后面有一个格式化环
  • 字符串内部的CCD_ 9告诉格式化器它是替换字段并且应该是"0";计算的">
  • 括号内的num是对变量的引用
  • :告诉格式化程序下面有一个格式化指定器设置
  • 0是应用于"填充"字符串的变量/值
  • CCD_ 13是变量CCD_ 14在新字符串上的对齐。>表示向右
  • 4是我们希望得到的字符串具有的最小字符数。如果num等于或大于4个字符的长度,则格式化程序将不执行任何操作

最新更新