替换位于之间的字符串 [英] Replace a string located between
问题描述
这是我的问题:在一个包含逗号的文本变量中,我尝试仅删除位于两个字符串之间的逗号(实际上是 [
和 ]
).例如使用以下字符串:
Here is my problem: in a variable that is text and contains commas, I try to delete only the commas located between two strings (in fact [
and ]
). For example using the following string:
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
用于整个变量,但我不能为它的一部分使用它.这个网站上有一些主题接近,但我没有设法利用它们来解决我自己的问题,例如:
I know how to use .replace
for the whole variable, but I can not do it for a part of it.
There are some topics approaching on this site, but I did not manage to exploit them for my own question, e.g.:
推荐答案
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
完成此操作).然后你重写那些部分.
First you need to find the parts of the string that need to be rewritten (you do this with re.sub
). Then you rewrite that parts.
函数var1 = re.sub("re", fun, var)
的意思是:找出te变量var
中符合"re的所有子串"
;使用函数 fun
处理它们;返回结果;结果将保存到 var1
变量中.
The function var1 = re.sub("re", fun, var)
means: find all substrings in te variable var
that conform to "re"
; process them with the function fun
; return the result; the result will be saved to the var1
variable.
正则表达式[[^]]*]"的意思是:找到以[
开头的子串(\[
in re),包含除之外的所有内容]
([^]]*
in re) 并以 ]
结尾 (\]
in re).
The regular expression "[[^]]*]" means: find substrings that start with [
(\[
in re), contain everything except ]
([^]]*
in re) and end with ]
(\]
in re).
对于每个发现的事件,运行一个函数,将这个事件转换为新的事件.功能是:
For every found occurrence run a function that convert this occurrence to something new. The function is:
lambda x: group(0).replace(',', '')
这意味着:取找到 (group(0)
) 的字符串,将 ','
替换为 ''
(删除 ','
>, 换句话说)并返回结果.
That means: take the string that found (group(0)
), replace ','
with ''
(remove ,
in other words) and return the result.
这篇关于替换位于之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!