簡體   English   中英

如何在字符串中間用前導零填充數字?

[英]How to pad a number with leading zeros in the middle of a string?

該列表的一個示例如下:

   Name
   KOI-234
   KOI-123
   KOI-3004
   KOI-21
   KOI-4325

我只是想讓所有這些數字至少有 4 個字符,所以它看起來像這樣:

   Name
   KOI-0234
   KOI-0123
   KOI-3004
   KOI-0021
   KOI-4325

我已經嘗試過這段代碼,但我猜它會將“KOI”部分讀取為非數字並且不添加零。

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

那么,我該如何實現呢?

您可以使用格式規范

lst = ['KOI-234', 'KOI-123', 'KOI-3004', 'KOI-21', 'KOI-4325']

['{}-{:0>4}'.format(*i.split('-')) for i in lst]
# ['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

您可以使用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)]]

Output:

['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]]

Output:

['Name', 'KOI-0234', 'KOI-0123', 'KOI-3004', 'KOI-0021', 'KOI-4325']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM