Python vs. Perl, which is better to learn?
Alex Martelli
aleax at aleax.it
Wed May 1 11:07:58 EDT 2002
Mark McEahern wrote:
...
>> s/^([^ ]* *([^ ]*)/$2 $1/; # reverse order of 2 words
>
> 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])
I suspect a closer match to the quoted perl code's intentions is:
s = re.sub(r'^(\S+)(\s+)(\S+)', r'\3\2\1', s)
though it's a bit hard to tell because it seems to me that neither the
original Perl (parentheses unbalanced) nor your Python (works on 1st
and last rather than first two words; uses wordcharacters rather than
white/nonwhite distinction) are correct.
Alex
More information about the Python-list
mailing list