How to split a string which has blank to list?

Question:

I have next code:

can="p1=a b c p2=d e f g"
new = can.split()
print(new)

When I execute above, I got next:

['p1=a', 'b', 'c', 'p2=d', 'e', 'f', 'g']

But what I really need is:

['p1=a b c', 'p2=d e f g']

a b c is the value of p1, d e f g is the value of p2, how could I make my aim? Thank you!

Asked By: ivy

||

Answers:

If you want to have ['p1=a b c', 'p2=d e f g'], you can split using a regex:

import re

new = re.split(r's+(?=w+=)', can)

If you want a dictionary {'p1': 'a b c', 'p2': 'd e f g'}, further split on =:

import re
new = dict(x.split('=', 1) for x in re.split(r's+(?=w+=)', can))

regex demo

Answered By: mozway

You can just match your desired results, looking for a variable name, then equals and characters until you get to either another variable name and equals, or the end-of-line:

import re

can="p1=a b c p2=d e f g"
re.findall(r'w+=.*?(?=s*w+=|$)', can)

Output:

['p1=a b c', 'p2=d e f g']
Answered By: Nick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.