删除引号内的空格

2024-06-16 10:50:54 发布

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

我试着去掉放在双引号内的短语前后的空格。我在google上找到的任何东西都删除了空格,但也删除了引号前后的空格。在

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."

代码如下:

^{pr2}$

预期输出为:

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

请帮忙。在


Tags: orandgooglebeare空格changedshould
3条回答

要运行的代码的修改版本是:

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)

输出:

^{pr2}$

说明: 我将匹配的\“+空格+(任何内容)+空格+\”替换为\“+(任何内容)+\” 其中()表示捕获组。所以我可以使用语法r'\1'

我不认为你能用regex做到这一点(至少不是在我的级别上),你需要循环字符串并计算\"的出现次数,以便在count为奇数之后或偶数之前移除空格。。。(只有在它们总是匹配的情况下才有效)

编辑对于已知报价总是匹配的情况,请参阅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)

相关问题 更多 >