Search code examples
pythonstringsubstring

python remove characters between quotes


I tried to remove characters between quotes.

Input string: "a string ,5,to",5,6,my,use,"123456,inside",1,a,b

I would like this output: 5,6,my,use,1,a,b

I tried with re.sub without success:

line = ['"a string ,5,to",5,6,my,use,"123456,inside",1,a,b']
substr = re.sub("[\"\].*?[\"\]", "", line)

many thanks for any help


Solution

  • You can match two double-quotes with zero or more non-double-quote characters in between, and substitute the match with an empty string. Also match an optional comma that follows to remove it:

    import re
    
    line = '"a string ,5,to",5,6,my,use,"123456,inside",1,a,b'
    print(re.sub(r'"[^"]*",?', '', line))
    

    This outputs:

    5,6,my,use,1,a,b
    

    Demo: https://replit.com/@blhsing/ConsiderableDapperBrain