Python vs. Perl, which is better to learn?
Ian Bicking
ianb at colorstudy.com
Wed May 1 16:21:20 EDT 2002
A few minor additions:
On Wed, 2002-05-01 at 08:58, Mark McEahern wrote:
> > A successful match sets a flurry of global variables:
> >
> > $& = the matched portion of the input string
> >
> > $` = everything before the match
> >
> > $' = everything after the match
>
> Thank Crom Python doesn't do that. As someone else mentioned, these things
> are tucked away into match objects, if you want them, rather than being
> squirted into your namespace.
In particular, if you do:
match = someRegex.search(s)
match.group(0) # Like $&
s[:match.start()] # Like #`
s[match.end():] # Like #'
match.group(x) # Like $x, where x is a number
Probably for any $ variable in Perl, there will be a fairly simple way
of getting the same result in Python.
> > Parentheses in the regex break the matching pattern into "groups" and the
> > portions of the string coresponding to each group may be accessed via:
> >
> > $1, $2, ...
> >
> > E.g.,
> >
> > 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])
Or you can do:
regex = re.compile(r'^([^ ]* *([^ ]*)')
transposed = regex.sub(lambda m: "%s %s" % (m.group(2), m.group(1)), s)
This is closer to the Perl example. The lambda may leave it a bit
difficult to read, though :) There must be something like
substitute-base-on-a-function in Perl, but it should be noted that while
it can be more awkward in some cases, it's also much more powerful than
the simple s/.../$2 $1/; substitution. For instance, a very simple
templating system can be:
templateRE = re.compile(r'%%(.*?)%%')
def subTemplate(source, valueDict):
return templateRE.sub(lambda m, valueDict=valueDict: valueDict.get(
m.group(1), ''), source)
Ian
More information about the Python-list
mailing list