[Tutor] don't understand iteration

Peter Otten __peter__ at web.de
Mon Nov 10 02:47:03 CET 2014


Clayton Kirkwood wrote:

> I have the following code:

>          blah =
> re.search(r'<\w\w>(\w{3}\.)\s+(\d{2}),\s+(\d{2}).+([AP]M)\s+(E[SD]T)',
> line)

>          (month, day, time, ap, offset) = blah.group(1,2,3,4,5)
> This works fine, but in the (month... line, I have blah.group(1,2,3,4,5),
> but this is problematic for me. I shouldn't have to use that 1,2,3,4,5
> sequence. I tried to use many alternatives using:  range(5) which doesn't
> work, list(range(5)) which actually lists the numbers in a list, and
> several others. As I read it, the search puts out a tuple. I was hoping to
> just assign the re.search to month, day, time, ap, offset directly. Why
> wouldn't that work? Why won't a range(5) work? I couldn't find a way to
> get the len of blah.

> What am I missing?

<https://docs.python.org/dev/library/re.html#re.match.groups>

While the direct answer would be

month, day, time, ap, offset = blah.group(*range(1,6))

there is also the groups() method

month, day, time, ap, offset = blah.groups()

which is appropriate when you want to unpack all capturing groups.





More information about the Tutor mailing list