Python 如何在字符串中间用前导零点填充数字?

Python 如何在字符串中间用前导零点填充数字?,python,list,Python,List,清单的一个例子如下: Name KOI-234 KOI-123 KOI-3004 KOI-21 KOI-4325 我只想让所有这些数字至少有4个字符,所以看起来是这样的: Name KOI-0234 KOI-0123 KOI-3004 KOI-0021 KOI-4325 我已经尝试过这个代码,但我猜它读取的“锦鲤”部分不是数字,也不会添加零 first_list = db['Name'] second_list = []

清单的一个例子如下:

   Name
   KOI-234
   KOI-123
   KOI-3004
   KOI-21
   KOI-4325
我只想让所有这些数字至少有4个字符,所以看起来是这样的:

   Name
   KOI-0234
   KOI-0123
   KOI-3004
   KOI-0021
   KOI-4325
我已经尝试过这个代码,但我猜它读取的“锦鲤”部分不是数字,也不会添加零

first_list = db['Name']
second_list = []
for pl in first_list:
    second_list.append(pl.zfill(4))

那么,我如何才能做到这一点呢?

您可以使用
str.split

n, *d = ['Name', 'KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']
result = [n, *[f'{a}-{b.zfill(4)}' for a, b in map(lambda x:x.split('-'), d)]]
输出:

['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']
['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']
如果你想计算偏移量的值:

n, *d = ['Name', 'KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']
_d = [i.split('-') for i in d]
offset = max(map(len, [b for _, b in _d]))
result = [n, *[f'{a}-{b.zfill(offset)}' for a, b in _d]]
输出:

['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']
['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']
您可以使用:

如果要删除前导零:

[f'{i}-{int(j)}' for i, j in map(lambda x: x.split('-'), lst)]

它不会添加零,因为每个元素/名称已经有4个以上的符号。 您可以尝试使用正则表达式:

import re

my_list = ['KOI-123', 'KOI-3004', 'KOI-21']
pattern = r'(?<=-)\w+'  # regex to capture the part of the string after the hyphen

for pl in my_list: 
     match_after_dash = re.search(pattern, pl)    # find the matching object after the hyphen
     pl = 'KOI-' + match_after_dash.group(0).zfill(4)    # concatenate the first (fixed?) part of  string with the numbers part
     print(pl)  # print out the resulting value of a list element
重新导入
my_list=['KOI-123','KOI-3004','KOI-21']

图案=r'(?它确实添加了零;在字符串的开头,文档说它会添加。如果您不想添加零,您必须指定。谢谢!并且,通过使用此方法,您能告诉我如何删除前导零吗?这样现在我就可以将“KOI-0001”改为“KOI-1”。@AugustoBaldo欢迎您!查看我编辑的答案。