470,849 Members | 1,634 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,849 developers. It's quick & easy.

Elegent solution to replacing ' and " ?

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.

May 6 '06 #1
3 973
Jim
Are you sure that your dB interface module doesn't do this for you?
What dB and interface are you using?

Jim

May 6 '06 #2
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/

May 6 '06 #3
I'm using PyGreSQL on a PostgreSQL db.

I didn't even include my SQL but Serge guessed right and that's what I
had. I changed it and it works now.

Thanks for the help! :)

May 6 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Jakanapes | last post: by
3 posts views Thread by middletree | last post: by
6 posts views Thread by Dan | last post: by
19 posts views Thread by Ornette | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.