Skip to content Skip to sidebar Skip to footer

Parse Equation To List Of Tuples In Python

I want to parse equations and get a list of tuples. For example, when I enter 2x = 4+3y, I want to get [('', '2', 'x', '='), ('','4','',''), ('+','3','y','')] This is my regex

Solution 1:

(\d*)(\w*) *(=) *(\d*)(\w*) *[+|\-|*|/] *(\d*)(\w*)

How about this regex?

It separates all operands and operators. (and inside operands it also splits number and variable).

For testing the regex I normally use https://regex101.com/ so you can build regex with live changes there.

Solution 2:

If you change the quantifier on the coefficient from +(one or more) to *(zero or more) then you should get the result you are after. You will also get an empty string match due to all the quantifiers now being * but you can filter out that match.

>>> import re
>>> e1 = "2x=4+3y">>> e2 = "2=x+3y">>> re.findall("([+-]*)([0-9]*)([a-z]*)([<=>]*)", e1)
[('', '2', 'x', '='), ('', '4', '', ''), ('+', '3', 'y', ''), ('', '', '', '')]
>>> re.findall("([+-]*)([0-9]*)([a-z]*)([<=>]*)", e2)
[('', '2', '', '='), ('', '', 'x', ''), ('+', '3', 'y', ''), ('', '', '', '')]

Note: whilst this solves your direct question this is not a good approach to parsing infix equations.

Post a Comment for "Parse Equation To List Of Tuples In Python"