"Literal replace" in SymPy
Question:
Is there a way to perform a "literal replacing" in SymPy, which matches exactly the pattern?
For example, for the expression exp(I*theta)+exp(-I*theta)
, I would like to replace only exp(It) to zero without replacing exp(-It)
A minimal example would be
from sympy import *
f=exp(I*t)+exp(-I*t)
Clearly, subs
will not work
f.subs((exp(I*t),0))
because it also replaces exp(-I*t)
with infinity.
Answers:
you can use the replace method —
t = 2
f = exp(I * t) + exp(-I * t)
f = f.replace(exp(I * t), 0)
print(f)
outputs:
exp(-2*I)
hope this helps!
You can use the xreplace
method:
f.xreplace({exp(I*t):0})
Returns:
exp(-t*I)
Here is the documentation for reference.
Is there a way to perform a "literal replacing" in SymPy, which matches exactly the pattern?
For example, for the expression exp(I*theta)+exp(-I*theta)
, I would like to replace only exp(It) to zero without replacing exp(-It)
A minimal example would be
from sympy import *
f=exp(I*t)+exp(-I*t)
Clearly, subs
will not work
f.subs((exp(I*t),0))
because it also replaces exp(-I*t)
with infinity.
you can use the replace method —
t = 2
f = exp(I * t) + exp(-I * t)
f = f.replace(exp(I * t), 0)
print(f)
outputs:
exp(-2*I)
hope this helps!
You can use the xreplace
method:
f.xreplace({exp(I*t):0})
Returns:
exp(-t*I)
Here is the documentation for reference.