用python中字符串中的单个反斜杠替换双反斜杠 [英] Replace a double backslash with a single backslash in a string in python

查看:264
本文介绍了用python中字符串中的单个反斜杠替换双反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道该主题的变体已在别处讨论过,但其他主题都没有帮助.

I know that variants of this topic have been discussed elsewhere, but none of the other threads were helpful.

我想把一个字符串从python交给sql.然而,字符串中可能会出现撇号 (').我想用反斜杠转义它们.

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)+";"

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

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

推荐答案

完全不要.
也不要连接 sql 查询,因为它们容易被 sql 注入.

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

这篇关于用python中字符串中的单个反斜杠替换双反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆