Split a string by spaces — preserving quoted substrings — in Python

后端 未结 16 858
心在旅途
心在旅途 2020-11-22 15:05

I have a string which is like this:

this is \"a test\"

I\'m trying to write something in Python to split it up by space while ignoring spac

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 15:41

    Speed test of different answers:

    import re
    import shlex
    import csv
    
    line = 'this is "a test"'
    
    %timeit [p for p in re.split("( |\\\".*?\\\"|'.*?')", line) if p.strip()]
    100000 loops, best of 3: 5.17 µs per loop
    
    %timeit re.findall(r'[^"\s]\S*|".+?"', line)
    100000 loops, best of 3: 2.88 µs per loop
    
    %timeit list(csv.reader([line], delimiter=" "))
    The slowest run took 9.62 times longer than the fastest. This could mean that an intermediate result is being cached.
    100000 loops, best of 3: 2.4 µs per loop
    
    %timeit shlex.split(line)
    10000 loops, best of 3: 50.2 µs per loop
    

提交回复
热议问题