Newbie question: string replace
Diez B. Roggisch
deets at nospam.web.de
Tue Oct 25 12:50:07 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?
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