python reg ex to include missing commas

后端 未结 2 1696
刺人心
刺人心 2021-01-15 13:22

I need to ensure an string to have comma separated values. The strings I read may have space separated values.

  • Some commas might be missing in my input string
2条回答
  •  鱼传尺愫
    2021-01-15 13:47

    Maybe it would be easier use findall, str.join and str.strip, finding the strings between quotes first then all non-whitespace:

    s = """ 1, ' unchanged 1' " unchanged  2 "  2.009, -2e15 3"""
    
    r = re.compile("[\'\"].*?[\'\"]|\S+")
    print(", ".join([x.strip(",") for x in r.findall(s)]))
    
    1, ' unchanged 1', " unchanged  2 ", 2.009, -2e11, ' unchanged 1', " unchanged  2 ", 2.009, -2e15, 35, 3
    

    If you don't want any space after the comma:

    print(",".join([x.strip(",") for x in r.findall(s)]))
    1,' unchanged 1'," unchanged  2 ",2.009,-2e15,3
    

提交回复
热议问题