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.
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.
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.
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.
Yes, . split() always preserves the order of the characters in the string.
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.
Have a look at the shlex
module, particularly shlex.split
.
>>> import shlex >>> shlex.split('This is "a test"') ['This', 'is', 'a test']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With