首页 > 解决方案 > Python中的转义+引号

问题描述

我想要做的是将转义字符放在 python 字符串中。让我解释。

我有字符串

str = 'station and the "Tren Bach"'

然后str将其格式化为大的“SQL”查询,malformed exception由于“Tren Bach”中间的双引号。

所以我尝试在格式化之前进行预处理,如下所示。

str = str.replace ('"', '\"')
sql.format(str)

但是在 sql 字符串中,没有逃逸。

其次我试过,

str = str.replace ('"', '\\"')
sql.format (str)

但是此时,sql中显示了双重转义。

我的预期如下。

str = 'station and the \"Tren Bach\"'

这样str就不会在sql语句中出问题了。

你会推荐其他方式吗?

标签: pythonpython-3.xstringreplace

解决方案


BigQuery 使用与标准 SQL略有不同的转义。您需要在查询中使用引号将值括起来,类似于 Python。例如:

s = '''SELECT ... WHERE my_field='station and the "Tren Bach"' '''
#               note quotes here ^                  and here ^

推荐阅读