perl regex to python

Andrew Dalke dalke at acm.org
Wed Feb 7 01:19:36 EST 2001


nlymbo at my-deja.com asked:
>Hi all, in perl i would do this to pick apart a date string:
>
>if ($date_str =~ m#(\d+)/(\d+)/(\d+)#) {
>  print "month: $1, $day: $2, $year: $3\n";
>}

The most obvious Python equivalent is

import string
month, day, year = string.split($date_str, "/")

or (in Python 2.0)

month, day, year = date_str.split("/")

This is not identical to what the Perl snippet does.
Eg, imagine "1/2/3/4/5/6/7/8"

My code will call this an error while your code
reads the first three numbers.  If you want the
less strict behaviour, ask again and someone will
likely point out a pure regex solution.  However,
it's much less common in Python to use regexps as
compared to Perl.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list