Replace a string located between

前端 未结 4 2029
说谎
说谎 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:17

    Here is a non-regex method. You can replace your [] delimiters with say [/ and /], and then split on the / delimiter. Then every odd string in the split list needs to be processed for comma removal, which can be done while rebuilding the string in a list comprehension:

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

提交回复
热议问题