I have a naive question. Is there a general method to use some codes like this

ex:=A C+B C-A D-B D;
factor_in(_,$A,B$);


to obtain $(A+B)(C-D)$?

You can use sympy.factor, e.g.
ex:= A C + B C - A D -  B D;

(I should probably add automatic conversion from sympy objects to Ex, so that you can avoid the __str__()).