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 do you parse a string with newlines into lists in Python?

I have a string output that I would like to break into separate lists between any occurrence of "Map".

string = "Map \n
North Prong\n
Nonspecific+\n
W\n
A\n
20\n
A\n
20\n
A\n
20\n
A\n
20\n
Map\n
South Prong\n
Nonspecific+\n
W\n
A\n
20\n
A\n
20\n
A\n
20\n
A\n
20\n
Map\n
Trailway Hike-in\n
Nonspecific+\n
W\n
A\n
50\n
A\n
50\n
A\n
50\n
A\n
50\n
Map\n
HF001\n
Honey Flat\n
R\n
R\n
R\n
R\n
R\n
Map\n
HF003\n
Honey Flat\n
R\n
A\n
R\n
R\n
R\n
Map\n
HF004\n
Honey Flat\n
R\n
R\n
R\n
R\n
R\n"

I need this broken down into separate list elements.

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

Desired Output:
[[‘North Prong’, ‘Nonspecific+’, ‘W’, ‘A’, ’20’, ‘A’, ’20’, ‘A’, ’20’, ‘A’, ’20’],[‘South Prong’, ‘Nonspecific+’, ‘W’, ‘A’, ’20’, ‘A’, ’20’, ‘A’, ’20’, ‘A’, ’20’],[‘Trailway Hike-in’, ‘Nonspecific+’, ‘W’, ‘A’, ’50’, ‘A’, ’50’, ‘A’, ’50’, ‘A’, ’50’],[‘HF001’, ‘Honey Flat’, ‘R’, ‘R’, ‘R’, ‘R’, ‘R’],[‘HF003’, ‘Honey Flat’, ‘R’, ‘A’, ‘R’, ‘R’, ‘R’],[‘HF004’, ‘Honey Flat’, ‘R’, ‘R’, ‘R’, ‘R’, ‘R’]]

>Solution :

The cue where to split into sublists seems to be Map. So you can split on Map first, then split the sublists at ‘\n’. You also need to skip the first empty element when splitting at Map (hence the [1:]) and get rid of leading and trailing whitespace using strip.

[[e.strip() for e in d.strip().split('\n')] for d in string.split('Map')[1:]]
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