Martha Pears
Martha Pears

Reputation: 149

How to parse a string in python?

I am trying to parse a string. Like if this is the string "(A (B (C D) (E F)) (G H))", then I want to parse it like A has children B and G, B has children C and E, and no one else has any children. So, I want the output to be ['A_B_G', 'B_C_E']

I'm doing something like:

lst=[]
str = (A (B (C D) (E F)) (G H))
lst.append(str.split(' '))

And then I'm stuck!

Could somebody give me an idea what to do next?

Upvotes: 2

Views: 181

Answers (1)

Vlad
Vlad

Reputation: 18633

I'd rather not hint too much, but you can start by converting the list into one like

['(', 'A', '(', 'B', ...]

and then you go over it taking different actions depending on the type of symbol you see e.g. (, ) or a letter.

Upvotes: 1

Related Questions