[Tutor] changing string in place

Martin Walsh mwalsh at mwalsh.org
Sat Jan 10 04:28:52 CET 2009


Jon Crump wrote:
> I'm still faced with the problem of the javascript months being 0
> indexed. I have to add 1 to group \2 in order to get my acurate
> date-string. Obviously I can't do
>
> print jdate.sub(r'"\1-\2+1-\3"', s)
>
> because the first argument to sub() is a string. How can I act on \2
> before it's substituted for the matched string?
>

Ah, sorry I missed that part the first time through.

The first argument to jdate.sub ('repl') can also be a function that
accepts an re.match object and returns a string, so something like the
following (*untested*) may be helpful:

jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)')

def repldate(match):
    y, m, d = map(int, match.groups())
    return '%04d-%02d-%02d' % (y, m+1, d)

print jdate.sub(repldate, s)

HTH,
Marty

> Thanks again,
> Jon


More information about the Tutor mailing list