Can you separate this "+2x-5y+8+2y"(there isnt any spaces between characters) like [+2x,-5y,+8,+2y] in python? How?
Asked
Active
Viewed 53 times
-1
-
related: https://stackoverflow.com/questions/43389684/how-can-i-split-a-string-of-a-mathematical-expressions-in-python/43389952 – Jean-François Fabre Dec 02 '20 at 15:26
-
Yes, it is possible. The complexity of a solution would depend on the pattern of expressions you want to parse. – PM 77-1 Dec 02 '20 at 15:27
1 Answers
0
if you know the pattern of the input for all which might come in, take a look at regular expressions
In your case, a solution could be something like
import re
a = "+2x-5y+8+2y"
print(re.findall(r"[+-]\d[xy]?", a))
re.findall(expression, input)
requires a regular expression and a argument which shall be parsed
In the above solution, the pattern [+-]\d[xy]?
consists of
[+-]
either a + or a - symbol\d
any digit, if you expect multiple digits use\d+
instead (+ meaning here "at least one repetition")[xy]?
one of the characters x and y, but it might be missing. If you expect other letters as well, add them inside these brackets

schetefan24
- 106
- 1
- 8