Python: string splitting

I have a bunch of math expressions stored as strings. Here's a short one:

stringy = "((2+2)-(3+5)-6)" 

I want to break this line down into a list containing ONLY the information in each “infraorbital phrase” (I am sure there is a better way to express this.) Thus, my income will be:

 ['2+2','3+5'] 

I have a couple of ideas on how to do this, but all the time I am faced with the “okay now what” problem.

For instance:

 for x in stringy: substring = stringy[stringy.find('('+1 : stringy.find(')')+1] stringlist.append(substring) 

It just works peachy to return 2 + 2, but this applies as much as possible, and I am completely silent about how to move about the rest ...

+4
source share
3 answers

One way to use regex:

 import re stringy = "((2+2)-(3+5)-6)" for exp in re.findall("\(([\s\d+*/-]+)\)", stringy): print exp 

Output

 2+2 3+5 
+2
source

You can use regular expressions, for example:

 import re x = "((2+2)-(3+5)-6)" re.findall(r"(?<=\()[0-9+/*-]+(?=\))", x) 

Result:

 ['2+2', '3+5'] 
+1
source

The answer and problems with regular expressions can be found on a similar question: Regular expression to match external brackets

+1
source

Source: https://habr.com/ru/post/1480598/


All Articles