繁体   English   中英

在python的字符串中用双反斜杠替换双反斜杠

[英]Replace a double backslash with a single backslash in a string in python

我知道该主题的变体已在其他地方进行了讨论,但其他所有线程均无济于事。

我想将字符串从python移交给sql。 但是,可能会在字符串中出现撇号(')。 我想用反斜杠将其转义。

sql = "update tf_data set authors=\'"+(', '.join(authors).replace("\'","\\\'"))+"\' where tf_data_id="+str(tf_data_id)+";"

但是,这将始终在我的字符串中给出\\\\' 因此,反斜杠本身被转义,并且sql语句不起作用。

有人可以帮助我还是给我一种替代的方式? 谢谢

根本不要。
也不要串联sql查询,因为这些查询容易进行sql注入。

而是使用参数化查询:

sql = "update tf_data set authors=%(authors)s where tf_data_id=%(data_id)s"
# or :authors and :data_id, I get confused with all those sql dialects out there


authors = ', '.join(authors)
data_id = str(tf_data_id)

# db or whatever your db instance is called
db.execute(sql, {'authors': authors, 'data_id': data_id})

您正在使用双引号引起来的字符串,但仍转义了其中的单引号。 这不是必需的,您所需要做的就是转义要在替换操作中使用的反斜杠。

>>> my_string = "'Hello there,' I said."
>>> print(my_string)
'Hello there,' I said.
>>> print(my_string.replace("'", "\\'"))
\'Hello there,\' I said.

请注意,我正在使用打印。 如果您只是要求Python在替换操作之后向您显示字符串的表示形式,您会看到双反斜杠,因为它们需要转义。

>>> my_string.replace("'", "\\'")
"\\'Hello there,\\' I said."

正如其他人提到的那样,如果您使用python包执行SQL,请使用提供的带有参数占位符的方法(如果有)。

我的回答解决了提到的转义问题。 使用带前缀r的字符串文字

print(r"""the\quick\fox\\\jumped\'""")

输出:

the\quick\fox\\\jumped\'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM