[Tutor] Substitution question...

Sean 'Shaleh' Perry shalehperry@attbi.com
Wed Feb 12 01:10:02 2003


On Tuesday 11 February 2003 20:34, montana wrote:
>
> What I would like to do is lopp off the 'xxxxx' and replace with 'yyy' =
so
> the previous example would end up with yyy1.html and yyy12.html.
>
> (of course the '1' and '12' could be any number that is between 1 and 2
> digits long)
>
> How can I accomplish this easily.
>

sounds like a regular expression to the rescue!

import re
my_re =3D re.compile(r'^.+?(\d+)\.html$')
new_name =3D 'bob'
filename =3D 'sean12.html'
print my_re.sub('%s\\1.html' % new_name, name)

bob12.html is the output.

The regex translates to: 'start at the beginning of the string.  Find a g=
roup=20
of characters (don't care which) followed by a group of numbers and ".htm=
l". =20
Store the group of numbers'.

The sub() call replaces the string with the new_name followed by the grou=
p of=20
numbers found and ".html" again.