Python vs. Perl, which is better to learn?

Fredrik Lundh fredrik at pythonware.com
Wed May 1 10:38:21 EDT 2002


Mark McEahern wrote:
> Here's a case where Python's ability to name groups is interesting:
>
> import re, time
> t = time.asctime()
> pat = re.compile("(?P<hour>\d{2})\:(?P<minute>\d{2})\:(?P<second>\d{2})")
> m = pat.search(t)
> if m:
>     print m.group('hour')
>     print m.group('minute')
>     print m.group('second')
> else:
>     print "Not found."

(you don't need to escape colons)

also note that if you pass multiple group numbers (or names)
to the group method, it returns the given matches as a tuple:

m = re.search("(\d{2}):(\d{2}):(\d{2})", t)
if m:
    hour, minute, second = m.group(1, 2, 3)

(down from five lines in the original perl example ;-)

</F>





More information about the Python-list mailing list