Learning Python now coming from Perl

Roy Smith roy at panix.com
Sat Dec 6 20:15:28 CET 2008

In article <014a96e0$0$20670$c3e8da3 at news.astraweb.com>,
 Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote:
> > For your first
> > project, pick something that's small enough that you think you could
> > tackle it in under 50 lines of Perl.
> Is there anything which *can't* be written in under 50 lines of Perl?
> Also, Perl REs are faster than Python REs, or so I'm told. Between the 
> speed and the convenience, Perl programmers tend to use RE's for 
> everything they can. Python programmers tend to use REs only for problems 
> that *should* be solved with REs rather than *can* be solved with a RE.

Well, as an old-time unix hacker (who learned REs long before Perl 
existed), my question to you would be, "Is there any problem which 
*shouldn't* be solved with an RE?" :-)

It's easy to go nuts with REs, and create write-only code. On the other 
hand, they are an extremely powerful tool.  If you are wise in the ways of 
RE-fu, they can not only be the most compact way to write something, but 
also the most efficient and even the most comprehensible.  Unfortunately, 
REs seem to be regarded as some kind of monster these days and few people 
take the time to master them fully.  Which is a shame.

One really nice feature of REs in Python is the VERBOSE flag.  It lets you 
write some way-complicated REs in a way which is still easy for somebody to 
read and understand.  Python's raw strings, and triple-quoted strings, also 
help reduce the sea of backslashes which often make REs seem much worse 
than they really are.

One of the reasons REs don't get used in Python as much as in Perl is 
because strings have useful methods like startswith(), endswith(), and 
split(), and also the "in" operator.  These combine to give you easy ways 
to do many things you might otherwise do with REs.

More information about the Python-list mailing list