Newbie question: string replace

Don beachbumdon2005 at yahoo.com
Wed Nov 16 12:33:36 EST 2005


Diez B. Roggisch wrote:
> usgog at yahoo.com wrote:
> > I have a config file with the following contents:
> > service A = {
> >   params {
> >     dir = "c:\test",
> >     username = "test",
> >     password = "test"
> >   }
> > }
> >
> > I want to find username and replace the value with another value. I
> > don't know what the username value in advance though. How to do it in
> > python?
>
> Could be done using regular expressions. Ususally for such tasks one
> would prefer pythons string manipulation functions, but if you want to
> preserve whitespace, I think a rex is in order here:
>
>
> import re, sys
>
>
> new_name = "foobar"
>
> rex = re.compile(r'(^.*username *=[^"]*")([^"]*)(".*$)')
> for line in sys.stdin:
>      m = rex.match(line)
>      if m is not None:
>          line = "%s%s%s\n" % (m.group(1), new_name, m.group(3))
>      sys.stdout.write(line)
>
>
>
> use with
> 
> python script.py < config_in > config_out
> 
> Regards,
> 
> Diez




More information about the Python-list mailing list