+ 6

[python] Splitting a string

Hi, I am bit new to python. I want to split a string something like this: x='print "Thank you"' #Some code The output should be: ['print', '"Thank you"'] as you can see it did not split Thank you inside " " How can I do that?? And Thanks is advance.

14th Oct 2018, 4:18 AM
LoystonLive
LoystonLive - avatar
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))))
14th Oct 2018, 8:02 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 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)
14th Oct 2018, 5:24 AM
Anna
Anna - avatar
+ 5
Thanks for you all!!!
14th Oct 2018, 1:19 PM
LoystonLive
LoystonLive - avatar
+ 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'].
14th Oct 2018, 11:30 AM
HonFu
HonFu - avatar
+ 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.
14th Oct 2018, 12:52 PM
HonFu
HonFu - avatar
0
do u not use ("+")=("+")!
15th Oct 2018, 3:49 PM
Graham Conquer
Graham Conquer - avatar
- 1
use split there
15th Oct 2018, 2:52 AM
md zubair
md zubair - avatar