sympy: group given expressions within other expressions, e.g. $a + 2 x y + b x + 2 x z$

46 Views Asked by At

I would like to use sympy to locate and group instances of a given symbolic expression within a set of expressions, so that the given expression may be replaced by a variable. For instance, with expressions like

a + 2 * x * y + b * x + 2 * x * z

I would like to group factors of an expression such as y + z, to obtain

a + b * x + 2 * x * (y + z)

and then substitute symbol w for y + z:

a + b * x + 2 * x * w

What is the proper way to achieve that?