confused00
confused00

Reputation: 2612

Change 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 make it change the order of the elements in the tuples? Like this for example:

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

The tuples might have more than 2 elements, so I don't want to merely reverse the order, or reverse the text before applying the regex and use some lookahead/lookbehind functions. I want to know whether I can somehow set the order in the RegEx the way I would give it a name with (?P<name>...)

Upvotes: 3

Views: 1227

Answers (3)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14965

Use finditer instead of 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')]

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8702

You can reverse the 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')]

Upvotes: 0

LarsVegas
LarsVegas

Reputation: 6832

You could use a 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)

Upvotes: 0

Related Questions