7 Answers
+ 8
#Similar to Anna's solution:
import re
x = 'hello "world hello" world "hello" "world" hello'
ptrn = re.compile(r'\s*(".*?")\s*')
print(list(filter(None, ptrn.split(x))))
+ 5
I would use regular expressions
https://code.sololearn.com/cSlTeAxq0sqB/?ref=app
(if the string is more complex and you want to split strings like 'test "test test" test test "test"', you'll need a more complex regex pattern)
+ 5
Thanks for you all!!!
+ 3
There are a few built-in ways as well.
1.) If you know beforehand that you want to split only at the first whitespace, you can write:
'1 2 3'.split(maxsplit=1)
You will then get only one cut -> two items: ['1', '2 3']
2.) If you have control over how the string looks, you can insert a special split-letter and split by that. I once did that when I wanted to transform nutritional data for a txt-file and back to list-format. I formatted like this:
'apple: 50 1 10 0.1'
And when I had to split that, I could go by the colon, writing:
mytext.split(':')
That got me ['apple', '50 1 10 0.1'].
+ 1
Mehran sanea, in Python you can also just use a different set of quotes on the outside, as the OP already had done in his given example.
This is not what the question was about.
0
do u not use ("+")=("+")!
- 1
use split there