在temp后面用空格分隔字符串

2024-04-20 01:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Port          Name               Status    Vlan      Duplex  Speed   Type

字符串str

^{pr2}$

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

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

Tags: 字符串name模板标题列表porttypestatus
2条回答

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

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

以上输出:

^{pr2}$

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

您没有提供列值如何格式化的信息,例如分隔符、转义符和字符串引号。基于您的示例,我想说的是,比较棘手的部分是name列,您必须从该列中提取每个排除项。这是一个快速的方法,您可以从那里开始:

# Get the first element
first = str.split()[0]
# Get the last part of the string, excluding name 
last = str.split()[::-1][0:5]
last = last[::-1]
# Get the name column via exclusion of the two parts previously calculated
middle = str.split(first)[1].split(last[0])[0].strip()
r_tmp = [first, middle]
result = r_tmp + last
print result

相关问题 更多 >