this are two strings
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
I need to check the length of each item in "a" and compare with "b". And if any "|" found in between item in "b" then it has to be concatenated with a's item, like this, "RD" ,"WR" and "A" should be concatenated with TYP_25 of a. how to Merge two strings based on this condition?
You have a |
character every 20 positions; split your strings into sections of 20 characters, and pair up the results:
def by_width(line, width=20, stripchars='|'):
i = 0
while i < len(line):
yield line[i:i+width].strip(stripchars)
i += width
Zip the results together gives:
>>> 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']
From there on out you can do what you want with the columns; in the above sample I merely put them together into lists of whitespace-stripped strings.
if the format is confirmed, I think this would be ok:
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
Using a zip
works, regardless of whether the widths are equal.
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
The output is
['PVT corner', 'Description']
['TYP_25', 'RD', 'WR', 'A']
['SLOW_125', 'RD', 'WR']
['SLOW_0', 'RD', 'WR']
['SLOW_40', 'RD', 'WR']
['FAST_125', 'RD', 'WR']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.