Another way to implement this is as follows:
Create a List
of Rules
to ReplaceAll
Variables
with 1:
rules1 = # -> 1 & /@ Variables[eq]
(* {a -> 1, b -> 1, c -> 1, d -> 1, e -> 1, f -> 1, g -> 1, h -> 1, i -> 1, j -> 1, k -> 1, l -> 1, m -> 1, n -> 1, o -> 1, p -> 1, q -> 1, r -> 1, s -> 1, t -> 1, u -> 1, v -> 1, w -> 1, x -> 1, y -> 1, z -> 1} *)
Join to the front of this list of rules a new list with the variables you don't want replaced with 1:
rules2 = Join[{a -> a, b -> b}, # -> 1 & /@ Variables[eq]]
(* {a -> a, b -> b, a -> 1, b -> 1, c -> 1, d -> 1, e -> 1, f -> 1, g -> 1, h -> 1, i -> 1, j -> 1, k -> 1, l -> 1, m -> 1, n -> 1, o -> 1, p -> 1, q -> 1, r -> 1, s -> 1, t -> 1, u -> 1, v -> 1, w -> 1, x -> 1, y -> 1, z -> 1} *)
Then use ReplaceAll with the new, second list of rules:
eq /. rules2
(* a b *)
You can combine these steps in a single expression, which avoids the creation of unnecessary symbols ("rules1" and "rules2" here):
eq /. Join[{a -> a, b -> b}, # -> 1 & /@ Variables[eq]]
(* a b *)
Replace[x^y + a/h - z + k, Except[a | x, _Symbol] -> 1, {0, Infinity}]
?Heads -> False
is the default forReplace
. $\endgroup$Pi
is a symbol too and you probably wouldn't want to replace it ... I'd rather make a list of all relevant symbols first and work with that. Just to make sure nothing is included that shouldn't be ... $\endgroup$eq /. Cases[ Variables[eq] , v : Except[a | d] :> v -> 1 ]
$\endgroup$Times @@ ToExpression /@ (StringReplace[Map[ToString, List @@ eq], Except[Characters["ab"]] -> "1"])
. Try. $\endgroup$