Looping with regex (Python) appending after match to a list

Henk_Ten_Cate :

So I'am trying to append every match of a string into a list with regex. So here is my code. It only doesn't work (properly) unfortunatly.

seq = 'ABABABBBASHDBDHBEHDBEDH'
Empty_list = []
regex_ex = re.finditer(r'.{3}', seq)
for x in regex_ex:
    Empty_list.append(x)
kederrac :

to access the value of your match you should use re.Match.group method:

for x in regex_ex:
    Empty_list.append(x.group())

you could replace your for loop code with a list comprehension:

Empty_list = [x.group() for x in  re.finditer(r'.{3}', seq)]
print(Empty_list)

output:

['ABA', 'BAB', 'BBA', 'SHD', 'BDH', 'BEH', 'DBE']

if you want a more compact code:

list(map(re.Match.group, re.finditer(r'.{3}', seq)))

output:

['ABA', 'BAB', 'BBA', 'SHD', 'BDH', 'BEH', 'DBE']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34445&siteId=1