简体   繁体   English

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

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

I know that variants of this topic have been discussed elsewhere, but none of the other threads were helpful. 我知道该主题的变体已在其他地方进行了讨论,但其他所有线程均无济于事。

I want to hand over a string from python to sql. 我想将字符串从python移交给sql。 It might however happen that apostrophes (') occur in the string. 但是,可能会在字符串中出现撇号(')。 I want to escape them with a backslash. 我想用反斜杠将其转义。

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

However, this will always give \\\\' in my string. 但是,这将始终在我的字符串中给出\\\\' Therefore, the backslash itself is escaped and the sql statement doesn't work. 因此,反斜杠本身被转义,并且sql语句不起作用。

Can someone help me or give me an alternative to the way I am doing this? 有人可以帮助我还是给我一种替代的方式? Thanks 谢谢

Simply don't. 根本不要。
Also don't concatenate sql queries as these are prone to sql injections. 也不要串联sql查询,因为这些查询容易进行sql注入。

Instead, use a parameterized query: 而是使用参数化查询:

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})

You're using double-quoted strings, but still escaping the single quotes within them. 您正在使用双引号引起来的字符串,但仍转义了其中的单引号。 That's not required, all you need to do is escape the backslash that you want to use in the replace operation. 这不是必需的,您所需要做的就是转义要在替换操作中使用的反斜杠。

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

Note that I'm using print. 请注意,我正在使用打印。 If you just ask Python to show you its representation of the string after the replace operation, you'll see double backslashes because they need to be escaped. 如果您只是要求Python在替换操作之后向您显示字符串的表示形式,您会看到双反斜杠,因为它们需要转义。

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

As others have alluded to, if you are using a python package to execute your SQL use the provided methods with parameter placeholders(if available). 正如其他人提到的那样,如果您使用python包执行SQL,请使用提供的带有参数占位符的方法(如果有)。

My answer addresses the escaping issues mentioned. 我的回答解决了提到的转义问题。 Use a String literal with prefix r 使用带前缀r的字符串文字

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

Output: 输出:

the\quick\fox\\\jumped\'

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

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