Change the order of elements found by re.findall

If I have a regex like this, for example:

>>> text = 'asd321zxcnmzasd5'
>>> re.findall('(asd)(\d*)', text)
[('asd', '321'), ('asd', '5')]

      

How can I change the order of elements in tuples? For example, for example:

[('321', 'asd'), ('5', 'asd')]

      

Tuples can have more than two elements, so I don't want to just reorder or reverse the text before applying the regex and use some lookahead / lookbehind functionality. I want to know if I can somehow set the order in RegEx the way I would call it by name(?P<name>...)

+3


source to share


3 answers


Use finditer

instead findall

:



>>> for res in re.finditer('(?P<str>asd)(?P<dig>\d*)', text):
...    print (res.group('dig'),res.group('str'))                                                                                                                          
... 
('321', 'asd')
('5', 'asd')

>>> [(res.group('dig'),res.group('str')) for res in re.finditer('(?P<str>asd)(?P<dig>\d*)', text)]                                                                                     
[('321', 'asd'), ('5', 'asd')]

      

+2


source


You can use namedtuple. Something like this (untested)



from collections import namedtuple

NT = namedtuple('NT', 'first second')

def my_order(m):
    new_order = []
    for item in m:
        new_order.append((item.second, item.first))
    return new_order


m = re.findall(NT('(asd)(\d*)'), text)
my_m = my_order(m)

      

0


source


You can reverse tuples using

a=[('asd', '321'), ('asd', '5')]
a= [tuple(reversed(i)) for i in a]
print a
print a[0][0]
[('321', 'asd'), ('5', 'asd')]

      

0


source







All Articles