如何确保多行字符串中的双引号

How to ensure double quote in multiline strings

我写了一个 SQL 查询,它使用从 WTForms 传入的数据作为参数。 如何确保变量上有双引号?

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

现在显示为

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

然后抛出错误。如何让它变成:

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

尝试转义多行中的双引号。

>>> 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"

Python 不会阻止您在多行字符串中使用双引号。只有当您将它们并排放置时才会出现问题 ("""")。您可以将双引号转义为 \" 或简单地在它们和三引号 (" """).

之间留下一个 space

转义:

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

select * from table
where dt_date >= "asdf"

Space 三引号前:

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

select * from table
where dt_date >= "asdf"