You can use Trott-Strzebonski or RuleCondition
or controlled evaluation; see Replacement inside held expression, which might be considered a duplicate.
Variations:
int = HoldForm[Integrate[x^n/(x + 1)^(n + 1), {x, 0, 1}]];
int /. e_Times :> Block[{n = 3}, e /; True]
int /. e_Times :> Block[{n = 3}, RuleCondition[e, True]]
(* HoldForm[Integrate[x^3/(1 + x)^4, {x, 0, 1}]] *)
But not:
int /. e_Times :> Block[{n = 3}, e]
(*
HoldForm[Integrate[
Block[{n = 3}, x^n/(x + 1)^(n + 1)],
{x, 0, 1}]]
*)
These also give the desired result:
int /. e_Times :>
With[{i = e /. n -> 3}, RuleCondition[i, True]]
int /. e : Times[n, __] | Plus[n, __] | Power[_, n] :>
With[{i = e /. n -> 3}, RuleCondition[i, True]]
int /. HoldForm[Integrate[i_, rest___]] :>
With[{e = i /. n -> 3}, HoldForm[Integrate[e, rest]]]
int /. HoldForm[f_[args___]] :>
Block[{n = 3}, HoldForm[f[##]] &[args]]
int /. HoldForm[f_[args___]] :>
(HoldForm[f[##]] & @@ ({args} /. n -> 3))
(* HoldForm[Integrate[x^3/(1 + x)^4, {x, 0, 1}]] *)
Note that the very first variation assumes all the instances of n
occur inside a Times
, which is true in the OP's example. The pattern e : Times[n, __] | Plus[n, __] | Power[_, n]
comprises other forms, but not all possible forms (e.g. not Sin[n] x
).
The last three variations are more general. The third to last allows the integrand to be evaluated; the last two allow all arguments to be evaluated, should n
appear in the limits of integration, say.
There is a difference between ReplaceAll
(... /. n -> 3
) and Block[{n = 3},...]
if n
appears in another function that holds its arguments, which does not occur in the OP's example. This applies to any of the variations above. In ReplaceAll
, the symbol n
will be replaced by 3
but not evaluated inside a function that holds its arguments. In Block
, since n
is not evaluated inside such a function, it won't be replaced by 3
.