Home > Mobile >  How do you parse a string with newlines into lists in Python?
How do you parse a string with newlines into lists in Python?

Time:04-03

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.

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

CodePudding user response:

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 data.split('Map')[1:]]

CodePudding user response:

Id say split using '\n' and then append a list of every 11 elements in a list

ans = []
words = string.split('\n')
for i in range(len(words)//11   1):
    ans.append(words[i*11: (i 1)*11])
  • Related