What pattern should I use to replace zeros and ones as exponents?

Question:

I am trying to replace certain values using regex in a binomial expression to replace the values equivalent to a determined constant x that has as exponent the numbers 1 and 0, example: binomial = "625x^4+1500x^3+1350x^2+540x^1+81x^0".

This is the pattern i am using: r'[a-z][^][0]'

but it is not returning the desired value "625x^4+1500x^3+1350x^2+540x+81".

What pattern should I use to replace 'x^1' and 'x^0' with an empty or null character like ''?

Asked By: ellhe-blaster

||

Answers:

I assume you actually want to keep the x in x^1 therefore we can use this expression with a lookbehind assertion which will not be part of the match.


binomial = "625x^4+1500x^3+1350x^2+540x^1+81x^0"

print(re.sub(r"[a-z]^0|(?<=[a-z])^1b", "", binomial))
# Output 
625x^4+1500x^3+1350x^2+540x+81

[^...] is a not in … expression ^ needs to be escaped.

Answered By: Daraan

You can use this regex:

x^([01])b

which will match x^ followed by 0 or 1, and replace using a replacer function that will return x if the exponent is 1, otherwise nothing:

binomial = "625x^4+1500x^3+1350x^2+540x^1+81x^0"
res = re.sub(r'x^([01])b', lambda m:'x' if m.group(1) == '1' else '', binomial)

Output:

625x^4+1500x^3+1350x^2+540x+81
Answered By: Nick

In regular expressions, ^ is a special character which matches either the start of the line or it can be used to exclude a group. If you want to match a literal ^ character you will need to escape it with a . Additionally, is a special character in python strings so you need to either add ‘r’ to the start or use \.

This should work (run the code snippet to demo the Python):

import re

binomial = "625x^4+1500x^3+1350x^2+540x^1+81x^0"
pattern = r'[a-z]^[01]'
s = re.sub(pattern, "", binomial)
print(f"{s=}")

<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

p.s. It is unclear from the question whether you want to do math to evaluate the string or not. If you do that will require a more complex regular expression with a replacer function. I would go through a tutorial and play around with regular expressions here

import re

binomial = "625x^4+1500x^3+1350x^2+540x^1+81x^0"
pattern = r'([a-z])^(d*)'

x = 2
scope = locals()

def replacer(match):
    var_name, pow = match.groups()
    pow = int(pow)
    r = eval(f"{var_name}**{pow}", scope)
    print(f"{var_name} ** {pow} = {r}")
    return f'*{r}'

s = re.sub(pattern, replacer, binomial)
s

<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Answered By: Modularizer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.