如何为 Python 2.7 转义字符串中的特殊字符

How to escape special characters in string for Python 2.7

我想为 Python 2.7.

转义字符串中的特殊字符

例如,如果我有:

str = "You're the best "dog" on earth."

我会:

str = "You\'re the best \"dog\" on earth."

我想要它,因为我正在使用 pymySQL 在 SQL 数据库中插入字符串,但我找不到执行此操作的方法。

我猜转义字符一定是这样的吧? (不太确定) 我也会找到一种方法来执行反向操作删除转义字符。

您的处理方式完全错误。将字符串插入 SQL 数据库时,您永远不需要转义特殊字符:始终使用参数化 SQL 查询,任何需要的转义都会为您完成。如果您开始尝试自己对字符串进行转义,那么您就是在向各种安全问题敞开您的代码。

with connection.cursor() as cursor:
    # Create a new record
    sql = "INSERT INTO `mytable` (`thestring`) VALUES (%s)"
    cursor.execute(sql, (str,))

如果您发现自己使用来自任何外部源的数据构建查询字符串,请停止并重新考虑:您永远不需要这样做。

您不需要为了 SQL 手动转义值 !让数据库 API 来处理。

  1. 在 Python 源代码中形成有效的字符串文字:

    str = "You're the best \"dog\" on earth."
    str = 'You\'re the best "dog" on earth.'
    str = """You're the best "dog" on earth."""
    

    这些都是等价的,您只需要转义用作字符串文字终止符的适当引号即可。

  2. 正确使用数据库API,不用担心转义。来自 the manual:

    sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
    cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    

    转义是通过分隔查询和值来处理的,而不是通过添加反斜杠。