How to ensure double quote in multiline strings
Asked Answered
U

2

6

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"
Unbeatable answered 23/6, 2016 at 13:13 Comment(2)
You could put literal double quotes into your triple-quoted string.Cyrenaic
does it have to be double quotes or would single ' quotes work too? If single quotes would work I'd recommend using %(date)r instead of s to get the code representation of the string (including string quotes)Cleotildeclepe
E
6

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"
Epicarp answered 23/6, 2016 at 13:35 Comment(0)
P
1

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"
Parenthesis answered 23/6, 2016 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.