Elegent solution to replacing ' and " ?

Serge Orlov Serge.Orlov at gmail.com
Fri May 5 23:35:34 EDT 2006


fyleow wrote:
> I'm trying to replace the ' and " characters in the strings I get from
> feedparser so I can enter it in the database without getting errors.
> Here's what I have right now.
>
> self.title = entry.title.encode('utf-8')
> self.title = self.title.replace('\"', '\\\"')
> self.title = self.title.replace('\'', '\\\'')
>
> This works just great but is there a more elegent way to do this?  It
> looks like maybe I could use the translate method but I'm not sure.

You should use execute method to construct sql statements. This is
wrong:

self.title = entry.title.encode('utf-8')
self.title = self.title.replace('\"', '\\\"')
self.title = self.title.replace('\'', '\\\'')
cursor.execute('select foo from bar where baz="%s" ' % self.title)

This is right:

self.title = entry.title
cursor.execute("select foo from bar where baz=%s", (self.title,))

The formatting style differs between db modules, take a look at
paramstyle description in PEP 249:
http://www.python.org/dev/peps/pep-0249/




More information about the Python-list mailing list