views:

4164

answers:

4

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?

+10  A: 

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.

Dave Webb
+1: If you're escaping quotes in a database query, you're doing the SQL wrong.
S.Lott
+1 > I was about to post the same thing :-)
Jon Cage
Excellent, now I just need a copy of Python 3.0.
Jonathan Prior
Why do you need Python 3.0 to use a parameterized SQL statement? They exist in all releases and all Postgres Python interfaces.
S.Lott
There are other features I need to use in Python 3.0.
Jonathan Prior
All Python 3.0 features are available in Python 2.6. Use that.
S.Lott
A: 

Single quote and double quote can be used to escape each other, see

>>> print('"foo"')
"foo"
>>> print("'foo'")
'foo'
cartman
A: 

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.

robertlayton
A: 

If you're using psycopg2 that has a method for escaping strings: psycopg2.extensions.adapt() See http://stackoverflow.com/questions/309945/how-to-quote-a-string-value-explicitly-python-db-api-psycopg2 for the full answer

Evgeny