将每个单/双qoutes替换为“或”

2024-04-29 12:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大约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替换每个单引号和双引号?你知道吗


Tags: textidsqlindextreninsertvalues
1条回答
网友
1楼 · 发布于 2024-04-29 12:45:04

您可以使用带有负lookback的简单正则表达式:

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

这需要用

\\\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。你知道吗

相关问题 更多 >