Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
f[x2_] = ToExpression[StringTake[ToString[x2], -1]] x2;
(*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?

share|improve this question
Use SetDelayed[] instead of Set[]. – J. M. Oct 10 '12 at 13:29
up vote 5 down vote accepted

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;
(* 3 a3*)

Have a look at this tutorial on Set and SetDelayed.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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