How to re.search () multiple templates in python?
I have a list like this:
['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring']
I want to get results in 4 different variables:
s1 = 't__f326ea56'
s2 = ['foo', 'some']
s3 = ['bar', 's']
s4 = ['quax', 'string']
Usually I could do a type search re.search(r'(.*)\t(.*)\t(.*)', lst).group(i)
to get s2, s3, s4. But I cannot search all 4 at the same time. Is there any special parameter in the module that I can use?
thank
source to share
You can use the method split()
in the module re
:
import re
s = ['t__f326ea56',
'foo\tbar\tquax',
'some\ts\tstring']
new_data = [re.split("\\t", i) for i in s]
s1 = new_data[0][0]
s2, s3, s4 = map(list, zip(*new_data[1:]))
Output:
s1 = 't__f326ea56'
s2 = ['foo', 'some']
s3 = ['bar', 's']
s4 = ['quax', 'string']
Edit:
for lists of lists:
s = [['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring'], ['second\tbar\tfoo', 'third\tpractice\tbar']]
new_s = [[re.split("\\t", b) for b in i] for i in s]
new_s
now saves:
[[['t__f326ea56'], ['foo', 'bar', 'quax'], ['some', 's', 'string']], [['second', 'bar', 'foo'], ['third', 'practice', 'bar']]]
To transpose data to new_s
:
new_s = [[b for b in i if len(b) > 1] for i in new_s]
final_s = list(map(lambda x: zip(*x), new_s))
final_s
will now save the data as it was, which you want:
[[('foo', 'some'), ('bar', 's'), ('quax', 'string')], [('second', 'third'), ('bar', 'practice'), ('foo', 'bar')]]
source to share
Using the "straight" function str.split()
:
l = ['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring']
items1, items2 = l[1].split('\t'), l[2].split('\t')
s1, s2, s3, s4 = l[0], [items1[0], items2[0]], [items1[1], items2[1]], [items1[2], items2[2]]
print(s1, s2, s3, s4)
Output:
t__f326ea56 ['foo', 'some'] ['bar', 's'] ['quax', 'string']
source to share