user1128088 user1128088 - 5 months ago 20
Python Question

How to ensure double quote in multiline strings

I wrote an SQL query which uses data passed in from WTForms as parameters.
How do I ensure double quotes on the variable?

q = """
select * from table
where dt_date >= %(date)s""" % {'date':date}


Right now it shows as

select * from table
where dt_date >= 23-06-2016


which then throws error. How to make it become:

select * from table
where dt_date >= "23-06-2016"

Answer

Python doesn't stop you from using double-quotes inside your multiline strings. The trouble is only when you place them next to each other (""""). You can either escape your double quotes as \" or simply leave a space between them and the triple-quotes (" """).

Escaping:

q = """
select * from table
where dt_date >= \"%(date)s\""""%{'date':date}
>>> print q

select * from table
where dt_date >= "asdf"

Space before the triple-quotes:

q = """
select * from table
where dt_date >= "%(date)s" """%{'date':date}
>>> print q

select * from table
where dt_date >= "asdf"