>> I have some confusion regarding when findall returns a list of strings
>> and when it returns a list of tuples.
>> Would appreciate an explanation.
>
>re is not my strongest suite but I'll have a go.
>
>My understanding of how findall works is that it returns a list of matches. If 
>groups are used in the pattern each match will be a tuple containing the 
>groups (if there is only one group in the pattern it will be a tuple of only 
>one element)

One nice trick/feature that I recently discovered is that it's possible to 
"turn off" groups by using "?:"

>>> import re

>>> re.findall("(python(?:ic)?)", "python")  
['python']

>>> re.search("(python(?:ic)?)", "python").group(2)

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    re.search("(python(?:ic)?)", "python").group(2)
IndexError: no such group
>>> re.findall("(python(ic)?)", "python")
[('python', '')]
>>> re.findall("(python(ic)?)", "pythonic")
[('pythonic', 'ic')]


Thought it'd be nice to share this. ;-)


Regards,
Albert-Jan

_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to