Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a string which has blank to list?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading