ArchieTiger
ArchieTiger

Reputation: 2243

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"

Upvotes: 6

Views: 8323

Answers (2)

th3an0maly
th3an0maly

Reputation: 3510

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"

Upvotes: 6

The Pjot
The Pjot

Reputation: 1859

Try escaping the double quotes in your multine.

>>> q = """
... select * from table
... where dt_date >= \"%(date)s\""""%{'date':date}
>>> q
'\nselect * from table\nwhere dt_date >= "23-06-2016"'
>>> print q

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

Upvotes: 1

Related Questions