# ToString in a function

f[x2_] = ToExpression[StringTake[ToString[x2], -1]] x2;
f[a3]
(*Out: 2 a3*)


I expected the output to be 3 a3, but apparently x2 isn't evaluated in ToString.

How would one construct a function that gives the expected result?

-
Use SetDelayed[] instead of Set[]. –  Ｊ. Ｍ. Oct 10 '12 at 13:29

You have to use SetDelayed to get the desired behaviour. If you use only set, then to ToString just sees x2, which is where the two is coming from.

So this gives the correct result:

f[x2_] := ToExpression[StringTake[ToString[x2], -1]] x2;
f[a3]
(* 3 a3*)


Have a look at this tutorial on Set and SetDelayed.

-