Python vs. Perl, which is better to learn?
Fredrik Lundh
fredrik at pythonware.com
Wed May 1 10:41:55 EDT 2002
Mark McEahern wrote:
> This switches the first and last words of a sentence. I didn't bother
> putting the period back in there or sentence-casing the new first word.
>
> import re
> s = "Explicit is better than implicit."
> pat = re.compile("^(\w+)(.* )(\w+)\.$")
> m = pat.search(s)
> if m:
> print "%s%s%s" % (m.groups()[2], m.groups()[1], m.groups()[0])
instead of using groups three times, you can pass multiple
arguments to the group method:
m = pat.search(s)
if m:
print "%s%s%s" % (m.group(3, 2, 1))
or you can use group references in the sub method:
print pat.sub(r"\1\2\3", s)
</F>
More information about the Python-list
mailing list