Replace a string located between

前端 未结 4 2023
说谎
说谎 2020-12-06 05:03

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 ]).

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 05:40

    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)
    

    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.

    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.

    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(',', '')
    

    That means: take the string that found (group(0)), replace ',' with '' (remove , in other words) and return the result.

提交回复
热议问题