[Tutor] don't understand iteration
__peter__ at web.de
Mon Nov 10 09:10:19 CET 2014
Clayton Kirkwood wrote:
>>From: Tutor [mailto:tutor-bounces+crk=godblessthe.us at python.org] On
>>Behalf Of Peter Otten
>>Sent: Sunday, November 09, 2014 5:47 PM
>>To: tutor at python.org
>>Subject: Re: [Tutor] don't understand iteration
>>Clayton Kirkwood wrote:
>>> I have the following code:
>>> blah =
>>> (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?
>>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.
> Still seems odd to me. Blah is a tuple, and would think that there should
> be a natural way to pull it apart.
It's not a tuple it's a
>>> type(re.search("", ""))
This type could implement iteration over its groups -- but it doesn't:
>>> list(re.search("", ""))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_sre.SRE_Match' object is not iterable
> One can iterate across a string or list
> easily, why not a tuple. I also would have thought that a range(5) would
> have worked. Isn't it an iterable?
group(*range(5)) gives you groups 0...4, but 0 is special (the whole match
>>> re.search("(a+)(b+)", "xxxaaabbzzz").group(0)
)and you don't seem to want that.
More information about the Tutor