Python: ValueError: unsupported format character ''' (0x27) at index 1

user1558746 picture user1558746 · Jul 27, 2012 · Viewed 53.1k times · Source

I'm trying to execute a query to search 3 tables in a database using MySQL through Python. Every time I try and execute the following string as a query, it gives me an error about concatenation in the string.

"SELECT fileid FROM files WHERE description LIKE '%" + search + "%' OR filename LIKE '%" + search + "%' OR uploader LIKE '%" + search + "%' ORDER BY fileid DESC"

This is the error it gives me:

ValueError: unsupported format character ''' (0x27) at index 1

If I remove the character it asks for then I have to also remove the %, which stops the query from actually working properly. What can I do to fix this, since I'm rather new to Python.

Thanks, Kris

Answer

Pochi picture Pochi · Jul 27, 2012

It looks like python is interpreting the % as a printf-like format character. Try using %%?

"SELECT fileid 
FROM files 
WHERE description LIKE '%%%s%%' 
    OR filename LIKE '%%%s%%' 
    OR uploader LIKE '%%%s%%' 
    ORDER BY fileid DESC" % (search, search, search)