escape single and double quotes

Damjan gdamjan at gmail.com
Thu Mar 24 10:24:32 EST 2005


> I'm working with a Python program to insert / update textual data into a
> PostgreSQL database. The text has single and double quotes in it, and I
> wonder: What is the easiest way to escape quotes in Python, similar to
> the Perlism "$str =~ s/(['"])/\\$1/g;"?
> 
> I tried the re.escape() method, but it escapes far too much, including
> spaces and accented characters. I only want to escape single and double
> quotes, everything else should be acceptable to the database.

You don't need to escape text when using the Python DB-API. 
DB-API will do everything for you.
For example:
 SQL = 'INSERT into TEMP data = %s'
 c.execute(SQL, """ text containing ' and ` and all other stuff we might 
  read from the network""")

You see, the SQL string contains a %s placeholder, but insetad of executing
the simple string expansion SQL % """....""", I call the execute method
with the text as a second *parametar*. Everything else is magic :).





-- 
damjan



More information about the Python-list mailing list