[Tutor] Fwd: findall() returns tuples or string?
suhas bhairav
suhasbhairav at hotmail.com
Thu Mar 7 06:26:43 CET 2013
Hi Alan,
As far as my understanding goes, re.findall without using "()" inside your pattern will return you a list of strings when you search something similar to the one shown below:
a="Bangalore, India"re.findall("[\w][\n]*",a)
Output:- ['B','a','n','g','a','l','o','r','e','I','n','d','i','a']
So the above output is a list of strings.
When you enclose your pattern within "()", it will return you the output as a list of tuples. The member of each tuple is a string.
a="Amherst, Massachusetts"re.findall("(Am)(herst)",a)Output:- [('Am','herst')]
So the above output is a list of tuples.
Let me know if you any questions.
RegardsSuhas
> Date: Wed, 6 Mar 2013 12:55:17 -0800
> From: fomcl at yahoo.com
> To: alan.gauld at btinternet.com; tutor at python.org
> Subject: Re: [Tutor] Fwd: findall() returns tuples or string?
>
>
>
> >> 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 - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130307/33dd7acf/attachment.html>
More information about the Tutor
mailing list