Q:

How can I replace'&' to '&' in python?

I'm having issues with .replace().  My XML parser does not like '&', but will accept '&\amp;'.  I'd like to use .replace('&','&amp;') but this does not seem to be working.  I keep getting the error:
lxml.etree.XMLSyntaxError: xmlParseEntityRef: no name, line 51, column 41

So far I have tried just a straight forward file=file.replace('&','&amp;'), but this doesn't work.  I've also tried:
xml_file = infile
file=xml_file.readlines()
for line in file:
        for char in line:
                char.replace('&','&amp;')
infile=open('a','w')
file='\n'.join(file)
infile.write(file)
infile.close()
infile=open('a','r')
xml_file=infile

What would be the best way to fix my issue?

A:

str.replace creates and returns a new string. It can't alter strings in-place - they're immutable. Try replacing:
file=xml_file.readlines()

with
file = [line.replace('&','&amp;') for line in xml_file]

This uses a list comprehension to build a list equivalent to .readlines() but with the replacement already made.

