1

Alright, Currently, if given a string like such:

A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,(F:0.6,G:0.7)H:0.8

I am using this:

child = Pstring[Pstring.find('(')+1:Pstring.find(')')]

To iterate through the string, and print out the inner parenthesis, and assign it to the variable 'child'

Now, my question is, how can I do the same for:

W:1.0,X:1.1(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,(F:0.6,G:0.7)H:0.8)Y:0.9  

Which just simply contains an outside parenthesis to show that everything(except W and X) are children of Y

I currently get an output of 'child' as:

A:0.1,B:0.2,(C:0.3,D:0.4

Whereas what I want the code to do is to first parse through the outside parenthesis, and grab the inner ones first, then work on the outside last.

Thanks!

0

1 Answer 1

3

If you just want the contents of the inner parentheses, you can use re.findall() with the following regular expression:

\(([^()]*)\)

For example:

>>> import re
>>> s = 'W:1.0,X:1.1(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,(F:0.6,G:0.7)H:0.8)Y:0.9'
>>> re.findall(r'\(([^()]*)\)', s)
['C:0.3,D:0.4', 'F:0.6,G:0.7']

Explanation:

\(        # literal '('
(         # start capturing group
  [^()]*    # any characters except '(' and ')', any number
)         # end capturing group
\)        # literal ')'

re.findall() returns the contents of the capturing group for each match.

Sign up to request clarification or add additional context in comments.

3 Comments

hmm, i am trying to keep the output as a string, and not as a list, as i need to further split and cut it up in the rest of my program
Was there a .find function that searched from the back of a string?
@Sean The result here is a list of strings, and you said you want to iterate through the string, so you can just iterate over the list to get each matching portion as a string. If this isn't what you need, edit your question to provide what you expect the output to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.