escaping % in a string???

A

Amy G

I am trying to execute the following MySQL query:

c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE '%%s%'"""
%(userid, phrase))

This returns an error saying:
ValueError: unsupported format character ''' (0x27) at index 63

I can fix this by setting
phrase = "%" + phrase + "%"

and then
c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE '%s'"""
%(userid, phrase))

But is there a way to escape the % signs in the first execute statement?

Thanks in advance for any help.
Sorry about the easy question.
 
W

Wolfram Kraus

Heyho!

Amy said:
I am trying to execute the following MySQL query:

c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE
'%%s%'""" %(userid, phrase))

Use %%
c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE
'%%%s%%'""" %(userid, phrase))

This returns an error saying: ValueError: unsupported format
character ''' (0x27) at index 63

I can fix this by setting phrase = "%" + phrase + "%"

and then c.execute("""DELETE FROM pending WHERE userid=%s AND subject
LIKE '%s'""" %(userid, phrase))

But is there a way to escape the % signs in the first execute
statement?

Thanks in advance for any help. Sorry about the easy question.

Stay Rude!
Wolfram
 
D

Duncan Booth

Use %%
c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE
'%%%s%%'""" %(userid, phrase))

You might also consider:

c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE %s""",
(userid, '%'+phrase+'%'))

This has the advantage that it should properly handle any odd characters
appearing in the parameters (especially important if the parameter text
could have come from a malicious user).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,835
Latest member
KetoRushACVBuy

Latest Threads

Top