这是两个字符串
a= PVT corner | TYP_25 | SLOW_125 | SLOW_0_ | SLOW_40 | FAST_125
b= Description | RD | WR | A | RD | WR | RD | WR | RD | WR | RD | WR
我需要检查“a”中每个项目的长度并与“b”进行比较。如果有“|”在“b”中的项目之间找到它然后它必须与一个项目连接,像这样, “RD”,“WR”和“A”应与a的TYP_25连接。 如何根据这个条件合并两个字符串?
答案 0 :(得分:4)
每20个职位有|
个字符;将您的字符串拆分为20个字符的部分,并将结果配对:
def by_width(line, width=20, stripchars='|'):
i = 0
while i < len(line):
yield line[i:i+width].strip(stripchars)
i += width
将结果拼凑在一起给出:
>>> for column_a, column_b in zip(by_width(a), by_width(b)):
... print [column_a.strip()] + [v.strip() for v in column_b.split('|')]
...
['PVT corner', 'Description']
['TYP_25_0P85', 'RD', 'WR', 'A']
['SLOW_125_0P765', 'RD', 'WR']
['SLOW_0_0P765', 'RD', 'WR']
['SLOW_M40_0P765', 'RD', 'WR']
['FAST_125_0P935', 'RD', 'WR']
从那里开始,你可以用列做你想做的事;在上面的示例中,我只是将它们放在一起列入空格剥离的字符串列表。
答案 1 :(得分:1)
如果确认格式,我认为这样就可以了:
tmp_flag1 = "#"
tmp_flag2 = "|"
tmp_str1 = a.replace(tmp_flag1, "")
tmp_str2 = b.replace(tmp_flag1, "")
tmp_str3 = ""
tmp_pos_head = 0
tmp_pos_tail = 0
tmp_is_equal = False
tmp_ret = tmp_str1.find(tmp_flag2)
while tmp_ret != -1:
tmp_pos_tail = tmp_ret
if tmp_str2[tmp_ret] == tmp_flag2:
tmp_buf1 = tmp_str1[tmp_pos_head:tmp_pos_tail].replace(tmp_flag2, "")
tmp_buf2 = tmp_str2[tmp_pos_head:tmp_pos_tail].replace(tmp_flag2, "")
tmp_str3 += tmp_buf1 + ":" + tmp_buf2 + "\n"
tmp_pos_head = tmp_ret + 1
tmp_is_equal = True
tmp_ret = tmp_str1.find(tmp_flag2, tmp_ret + 1)
if tmp_is_equal == True:
tmp_buf1 = tmp_str1[tmp_pos_tail:].replace(tmp_flag2, "")
tmp_buf2 = tmp_str2[tmp_pos_tail:].replace(tmp_flag2, "")
else:
tmp_buf1 = tmp_str1[tmp_pos_head:].replace(tmp_flag2, "")
tmp_buf2 = tmp_str2[tmp_pos_head:].replace(tmp_flag2, "")
tmp_str3 += tmp_buf1 + ":" + tmp_buf2
print tmp_str3
答案 2 :(得分:1)
无论宽度是否相等,使用zip
都可以。
a = " PVT corner | TYP_25 | SLOW_125 SLOW_0_ | SLOW_M40| FAST_12 "
b = " Description | RD | WR | A | RD | WR | RD | WR | RD | WR | RD | WR "
head = 0
res = []
for i,(s,t) in enumerate(zip(a,b)):
if (s,t) == ("|","|"):
res.append([a[head:i].strip()]+[m.strip() for m in b[head:i].split("|")])
head = i + 1
res.append([a[head:].strip()]+[m.strip() for m in b[head:].split("|")])
for r in res:
print r
输出
['PVT corner', 'Description']
['TYP_25', 'RD', 'WR', 'A']
['SLOW_125', 'RD', 'WR']
['SLOW_0', 'RD', 'WR']
['SLOW_40', 'RD', 'WR']
['FAST_125', 'RD', 'WR']