Home > database >  How to split a string which has blank to list?
How to split a string which has blank to list?

Time:08-31

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!

CodePudding user response:

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

CodePudding user response:

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']
  • Related