A good way to escape quotes in a database query string?
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 it's part of a Database query you should be able to use a Parameterized SQL Statement.
As well as escaping your quotes, this will deal with all special characters and will protect you from SQL injection attacks.
Use json.dumps
.
>>> import json
>>> print json.dumps('a"bc')
"a\"bc"
Triple single quotes will conveniently encapsulate the single quotes often used in SQL queries:
c.execute('''SELECT sval FROM sdat WHERE instime > NOW() - INTERVAL '1 days' ORDER BY instime ASC''')