Regex replacement operation

David K. Trudgett dkt at registriesltd.com.au
Wed Jan 15 23:37:25 EST 2003


I'm trying to write a little micro function in Python that takes a
string with numeric dates in it and changes those dates into an
ISO8601 format. The dates in the input string are in a consistent
format, so that simplifies it. In Perl, I could write something like
the following to do it:

$str = 'Today is 16-1-2003 or 16-01-2003. New Year was 1-1-2003, reportedly.';

$str =~ s/ \b (\d{1,2}) - (\d{1,2}) - (\d{4}) \b /
    $3 . '-' . sprintf('%02d', $2) . '-' . sprintf('%02d', $1) /gxe;

which would make $str contain:

"Today is 2003-01-16 or 2003-01-16. New Year was 2003-01-01, reportedly."


How would I go about doing that in Python?

I've looked up the "re" module, but don't see any "substitute"
command, so it seems a different approach may be in order.

Thanks.

David Trudgett








More information about the Python-list mailing list