gpt4 book ai didi

python - 根据模板使用空格分割字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:56 24 4
gpt4 key购买 nike

我有以下字符串标题(模板):

Port          Name               Status    Vlan      Duplex  Speed   Type

和字符串str:

Eth1/2        trunk to dg-qwu-29 connected trunk     full    1000    1/10g

使用 header ,如何将 str 剥离到以下列表?

[Eth1/2, trunk to dg-qwu-29, connected, trunk, full, 1000, 1/10g]

最佳答案

以下内容假设行和标题遵循空白掩码。也就是说,标题文本与行列对齐。

import re
header = "Port Name Status Vlan Duplex Speed Type"
row = "Eth1/2 trunk to dg-qwu-29 connected trunk full 1000 1/10g"
# retrieve indices where each header title begins and ends
matches = [(m.group(0), (m.start(), m.end()-1)) for m in re.finditer(r'\S+', header)]
b,c=zip(*matches)
# each text in the row begins in each header title index and ends at most before the index
# of the next header title. strip() to remove extra spaces
items = [(row[j[0]:(c[i+1][0] if i < len(c)-1 else len(row))]).strip() for i,j in enumerate(c)]
print items

以上输出:

['Eth1/2', 'trunk to dg-qwu-29', 'connected', 'trunk', 'full', '1000', '1/10g']

编辑:从 https://stackoverflow.com/a/13734572/1847471 检索索引

关于python - 根据模板使用空格分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33273077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com