这里是我的问题:在一个包含逗号的文本变量中,我试图只删除位于两个字符串之间的逗号(实际上是[
和]
)。例如,使用以下字符串:
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
,但我不能对其中的一部分使用它。在这个网站上有一些主题正在接近,但我没有设法利用它们来回答我自己的问题,例如:
Repeatedly extract a line between two delimiters in a text file, Python
Python finding substring between certain characters using regex and replace()
replace string between two quotes
最佳答案
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 variablevar
中查找符合"re"
的所有子字符串;使用函数fun
处理它们;返回结果;结果将保存到var1
变量。正则表达式“[^]]*”表示:查找以
[
(\[
in re)开头、包含除]
([^]]*
in re)和以]
(\]
in re)结尾的所有子字符串。对于每个找到的事件,运行一个将此事件转换为新事件的函数。
功能是:
lambda x: group(0).replace(',', '')
这意味着:获取找到的字符串(
group(0)
),将','
替换为''
(换句话说,移除,
)并返回结果。关于python - 替换位于其间的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11096720/