【问题标题】:replace evey single/double qoutes with \' or \"用 \' 或 \" 替换每个单引号/双引号
【发布时间】:2019-02-25 09:23:54
【问题描述】:

我有大约 6000 条记录,我想将它们和INSERT 读取到新表中。它们包含单引号和双引号,而 MySQL 无法接受我的查询,因为当阻止我的 '(单引用)它已被关闭并产生语法错误:

sql = "INSERT INTO tr_en_ahmadali(id,sura,aya,aya_text) VALUES({0},{1},{2},'{3}');".format(str(index), str(j[index - 1]) ,str(aya_), str(k[single_aya - 1]))
print(sql)

当我打印我的查询时,我得到以下 sql 查询:

INSERT INTO tr_en_ahmadali(id,sura,aya,aya_text) VALUES(34,2,27,'Who, having sealed it, break God's covenant, dividing what He ordained cohered; and those who spread discord in the land will suffer assuredly.');

我的问题是: 如何用 python 替换每个单引号和双引号 \' 或 \"?

【问题讨论】:

  • 使用format 或字符串连接来创建SQL 查询是危险的并且容易出错。使用execute 方法的强大功能:db.execute("INSERT INTO tr_en_ahmadali(id, sura, aya, aya_text) VALUES(?, ?, ?, ?)", (index, j[index - 1], aya_, k[single_aya - 1]))

标签: python sql string


【解决方案1】:

您可以使用带有否定后视的简单正则表达式:

(?<!\\)(["'])

这需要替换为

\\\1

a demo on regex101.com


Python 的全部内容:
import re

string = """This ain't funny, you know.
But this escaped one (\") won't change."""

rx = re.compile(r'''(?<!\\)(["'])''')

string = rx.sub(r'\\\1', string)
print(string)

another demo on ideone.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多