I\'ve tried all manner of Python modules and they either escape too much or in the wrong way. What\'s the best way you\'ve found to escape quotes (\", \') in Python?
For a solution to a more generic problem, I have a program where I needed to store any set of characters in a flat file, tab delimited. Obviously, having tabs in the 'set' was causing problems.
Instead of output_f.write(str), I used output_f.write(repr(str)), which solved my problem. It is slower to read, as I need to eval() the input when I read it, but overall, it makes the code cleaner because I don't need to check for fringe cases anymore.
The easy and standard way to escape strings, and convert other objects to programmatic form, is to use the built in repr()
function. It converts an object into the representation you would need to enter it with manual code.
E.g.:
s = "I'm happy I am \"here\" now"
print repr(s)
>> 'I\'m happy I am "here" now'
No weird hacks, it's built in and it just works for most purposes.
If using psycopg2, its execute()
method has built-in escaping:
cursor.execute("SELECT column FROM table WHERE column=%s AND column2=%s", (value1, value2))
Note, that you are giving two arguments to execute method (string and tuple), instead of using Python's % operator to modify string.
Answer stolen from here: psycopg2 equivalent of mysqldb.escape_string?