1
$\begingroup$

I'm trying to use ReplaceAll in a subscript. However, it doesn't seem to work as expected if I want to use the output the subscript in a ToString. See below:

Subscript[A, 1] /. Subscript[A, x_] -> x
Subscript[A, 1] /. Subscript[A, x_] -> ToString[x]
Subscript[A, 1] /. Subscript[A, x_] -> f[x]
1
x
f[1]

The first and third cases are resulting in the expected output, but ToString seems to have some special attribute that doesn't allow the replacement rule to process in the second case. What is causing this behaviour?

$\endgroup$
0

2 Answers 2

5
$\begingroup$

There is nothing special about ToString. In this kind of replacement you need to use RuleDelayed, :>.

Subscript[A, 1] /. Subscript[A, x_] :> ToString[x]

Try applying Trace to both forms of the expression and compare the order things are evaluated.

$\endgroup$
1
$\begingroup$
Subscript[A, 1] /. Subscript[A, x_] -> x // ToString
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.