Replace a string located between

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

    If you don't fancy learning regular expressions (see other responses on this page), you can use the partition command.

    sentence = "the quick, brown [fox, jumped , over] the lazy dog"
    left, bracket, rest = sentence.partition("[")
    block, bracket, right = rest.partition("]")
    

    "block" is now the part of the string in between the brackets, "left" is what was to the left of the opening bracket and "right" is what was to the right of the opening bracket.

    You can then recover the full sentence with:

    new_sentence = left + "[" + block.replace(",","") + "]" + right
    print new_sentence # the quick, brown [fox jumped over] the lazy dog
    

    If you have more than one block, you can put this all in a for loop, applying the partition command to "right" at every step.

    Or you could learn regular expressions! It will be worth it in the long run.

提交回复
热议问题