Why doesn’t ToString work in ReplaceAll? [duplicate]

This question already has an answer here:

Unexpected behavior of rule matching a pattern

2 answers

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?

=================

=================

2 Answers
2

=================

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.

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