Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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.

like image 452
Adam Pierce Avatar asked Sep 17 '08 04:09

Adam Pierce


People also ask

How do you split a string into substrings in Python?

Python split() Method Syntax When you need to split a string into substrings, you can use the split() method. In the above syntax: <string> is any valid Python string, sep is the separator that you'd like to split on.

How do you split a string by separated by space in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string into a list of substrings?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by substring in Python, pass the substring as a delimiter to the split() function.

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string.


2 Answers

You want split, from the built-in shlex module.

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

This should do exactly what you want.

like image 105
Jerub Avatar answered Oct 25 '22 03:10

Jerub


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

>>> import shlex >>> shlex.split('This is "a test"') ['This', 'is', 'a test'] 
like image 21
Allen Avatar answered Oct 25 '22 02:10

Allen