Replace string except inside quotes?

Raymond Hettinger vze4rx4y at verizon.net
Fri Dec 3 22:06:56 EST 2004


<beliavsky at aol.com> wrote > The code
>
> for text in open("file.txt","r"):
>     print text.replace("foo","bar")[:-1]
>
> replaces 'foo' with 'bar' in a file, but how do I avoid changing text
> inside single or double quotes? For making changes to Python code, I
> would also like to avoid changing text in comments, either the '#' or
> '""" ... """' kind.

The source for the tokenize module covers all these bases.


Raymond Hettinger





More information about the Python-list mailing list