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


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 spaces within quotes. The result I'm looking for is:

['this','is','a test']

PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.

2/7/2009 10:46:20 PM

Accepted Answer

You want split, from the shlex module.

>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']

This should do exactly what you want.

6/17/2016 8:09:47 PM

Have a look at the shlex module, particularly shlex.split.

>>> import shlex
>>> shlex.split('This is "a test"')
['This', 'is', 'a test']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow