I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
This naturally barfs with:
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks!
When needing a literal % inside a Python formatting expression, use %%:
statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)
See the documentation section 5.6.2. String Formatting Operations for more information.
You don't need to use string interpolation. The execute method handles it for you, so you can do this instead:
statmt="select id from %s WHERE `email` LIKE %blah%"
self.cursor.execute(statmt, tbl)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With