MAB
MAB

Reputation: 565

Regex in Python Equation Replacement

I'm somewhat new to regex and Python and am in the following situation. I'd like to take an equation string, like "A + B + C + 4D", and place the number 1 in front of all variables that have no number in front of them. So something like:

>>> foo_eqn = "A + B + C + 4D"
>>> bar_eqn = fill_in_ones(foo_eqn)
>>> bar_eqn
"1A + 1B + 1C + 4D"

After some research and asking, I came up with

def fill_in_ones(in_eqn):
    out_eqn = re.sub(r"(\b[A-Z]\b)", "1"+ r"\1", in_eqn, re.I)
    return(out_eqn)

However, it looks like this only works for the first two variables:

>>> fill_in_ones("A + B")
1A + 1B
>>> fill_in_ones("A + B + E")
1A + 1B + E
>>> fill_in_ones("2A + B + C + D")
2A + 1B + 1C + D

Anything really obvious I'm missing? Thanks!

Upvotes: 2

Views: 70

Answers (1)

turbulencetoo
turbulencetoo

Reputation: 3681

Looks like the re.I (ignore case flag) is the culprit:

>>> def fill_in_ones(in_eqn):
...     out_eqn = re.sub(r"(\b[A-Z]\b)", "1"+ r"\1", in_eqn)
...     return(out_eqn)
...
>>>
>>> fill_in_ones("A + 3B + C + 2D + E")
'1A + 3B + 1C + 2D + 1E'

This is because the next positional argument to re.sub is count, not flags. You'll need:

def fill_in_ones(in_eqn):
    out_eqn = re.sub(r"(\b[A-Z]\b)", "1"+ r"\1", in_eqn, flags=re.I)
    return(out_eqn)

Unfortunately, the re.I flag happens to be 2:

>>> import re
>>> re.I
2

Upvotes: 4

Related Questions