Python 删除引号内的空格

Python 删除引号内的空格,python,regex,Python,Regex,我试图删除放在双引号内的短语前后的空格。无论我在谷歌上找到什么,都会删除空格,但也会删除引号前后的空格 txt = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed." # output: "election laws\"are outmoded or inadequate and often ambiguous\"and should be changed."

我试图删除放在双引号内的短语前后的空格。无论我在谷歌上找到什么,都会删除空格,但也会删除引号前后的空格

txt = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."

# output:
"election laws\"are outmoded or inadequate and often ambiguous\"and should be changed."
代码如下:

import re

regex = r"(?<=[\"]) +| +(?=[\"])"

test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."

subst = ""

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

请帮助。

我认为你不能用正则表达式来做这件事(至少不是在我的级别上),你需要循环字符串并计算
\“
的出现次数,以便在计数为奇数之后或偶数之前删除空格…(这只适用于假设它们总是匹配的情况)


编辑对于已知引号总是匹配的情况,请参阅Pedro Torres的答案

一种可能是拆分字符串,然后将其连接起来,对每个区块应用不同的处理方法:

test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed."
print(test_str)

test=test_str.split("\"")
test[1]=test[1].strip()
test = "\"".join(test)

print(test)

要使用的代码的修改版本是:

import re

regex = '\\"\s+([^"]+)\s+\\"'

test_str = "election laws \" are outmoded or inadequate and often ambiguous \" and should be changed \" second quotes \"."

subst = ""

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, '\"'+r'\1'+'\"' , test_str)

if result:
    print (result)
输出:

election laws "are outmoded or inadequate and often ambiguous" and should be changed "second quotes".
说明: 我将匹配的\“+空格+(任意)+空格+\”替换为\“+(任意)+\”
其中()表示捕获组。因此,我可以使用语法r'\1'

引用此捕获组。我不懂python,但关于正则表达式的java.Briliant页面是您可以使用它来适应给定的正则表达式或找到另一个答案

你的问题取决于是否只有一对引号。如果只有一对,答案是存在的,比如:regex: ^(.?") ?(.?) ?"(.*)$ 替换 $1$2“$3

但是,如果有多对,则必须担心配对的开始和结束。它们是否可以嵌套?你能保证撇号的内部不能是单撇号吗?即使你能做到这一切,并保证它总是:'开始'结束'开始'结束…,因为每个撇号都有不同的处理取决于它是开始还是结束,你必须匹配整个片段,然后重复,这将导致不同数量的捕获组。我相信即使是最理想的情况也不可能通过简单的正则表达式替换。我相信,你的问题还有更多的问题,这将使它变得更加不可能


Buch检查该网页,您将找不到更好的文档。

如果有多对引号,则此操作无效更新答案,因此它可以使用多对引号谢谢。这很有帮助。没问题,请注意,佩德罗·托雷斯(Pedro Torres)的最新答案似乎很有效,而且应该是可能的,将接近的引号组合在一起,忽略不匹配的引号。此外,如果这些答案中的一个让你做你想要的,请考虑接受它(再一次,我建议Pedro Torres)有一个你发布的代码的修改,我把它放在下面的一个为你的输入工作的答案中。
election laws "are outmoded or inadequate and often ambiguous" and should be changed "second quotes".