Newbie question: string replace

davideugenewarren at gmail.com davideugenewarren at gmail.com
Tue Oct 25 13:26:26 EDT 2005


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?

>>> import re
>>> s = """service A = {
  params {
    dir = "c:\test",
    username = "test",
    password = "test"
  }

}"""
>>> usr_str = r'username = ".*",'
>>> usr_reg = re.compile(usr_str)
>>> usr_reg.sub('username = "%s",' % ('new_usr'),s)
'service A = {\n  params {\n    dir = "c:\test",\n    username =
"new_usr",\n    password = "test"\n  }\n\n}'




More information about the Python-list mailing list