替换位于

2024-04-28 17:47:47 发布

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

这里是我的问题:在一个文本变量中,我试图只删除位于两个字符串之间的逗号(实际上是[])。例如,使用以下字符串:

input =  "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
output = "The sun shines, that's fine [not for everyone] and if it rains, it Will Be better."

我知道如何对整个变量使用.replace,但不能对其中的一部分使用。 在这个网站上有一些主题正在接近,但我没有设法利用它们来回答我自己的问题,例如:


Tags: andthe字符串forifthatnotit
3条回答

这是一个非正则表达式方法。您可以用[//]替换[]分隔符,然后在/分隔符上split。然后,拆分列表中的每个odd字符串都需要进行comma删除处理,这可以在列表理解中重建字符串时完成:

>>> Variable = "The sun shines, that's fine [not, for, everyone] and if it rains,
                it Will Be better."
>>> chunks = Variable.replace('[','[/').replace(']','/]').split('/')
>>> ''.join(sen.replace(',','') if i%2 else sen for i, sen in enumerate(chunks))
"The sun shines, that's fine [not for everyone] and if it rains, it Will Be 
 better."

您可以使用这样的表达式来匹配它们(如果括号是平衡的):

,(?=[^][]*\])

使用类似于:

re.sub(r",(?=[^][]*\])", "", str)
import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)

首先需要找到需要重写的字符串部分(使用re.sub执行此操作)。然后你重写那些部分。

函数var1 = re.sub("re", fun, var)的意思是:在te变量var中找到符合"re"的所有子串;用函数fun处理它们;返回结果;结果将保存到var1变量。

正则表达式“[[^]]*”表示:查找以[(re中的\[)开头、包含除](re中的[^]]*)之外的所有内容并以](re中的\])结尾的子字符串。

对于找到的每个事件,运行一个函数将此事件转换为新事件。 功能是:

lambda x: group(0).replace(',', '')

这意味着:获取找到的字符串(group(0)),用''替换','(换句话说,删除,),并返回结果。

相关问题 更多 >