Replace a double backslash with a single backslash in a string in python

烈酒焚心 提交于 2021-02-08 10:09:28

问题


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

Can someone help me or give me an alternative to the way I am doing this? Thanks


回答1:


Simply don't.
Also don't concatenate sql queries as these are prone to sql injections.

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



回答2:


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.

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



回答3:


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

My answer addresses the escaping issues mentioned. Use a String literal with prefix r

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

Output:

the\quick\fox\\\jumped\'


来源:https://stackoverflow.com/questions/37030067/replace-a-double-backslash-with-a-single-backslash-in-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!