简体   繁体   中英

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

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

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

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\'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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