ToExpression[ToString[x^2]] does not produce $x^2$, instead it gives $x$. Please explain.

I actually wrote the following code and it gave the answer as 1.

C1 = (Subscript[x, 1][t] - Subscript[x, 0])^2 + (Subscript[y, 1][t] - 
     Subscript[y, 0])^2 - Subscript[l, 01]^2;
ToExpression[StringDelete[ToString[C1], "[t]"]]

Then I tried with $x^2$ to get $x$ only.


closed as off-topic by Alexey Popkov, Henrik Schumacher, m_goldberg, MarcoB, Carl Lange May 31 at 17:16

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Alexey Popkov, Henrik Schumacher, m_goldberg, MarcoB, Carl Lange
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 6
    $\begingroup$ Always look at intermediate results. Look at what ToString produces and it will be clear what happens. It uses OutuptForm by default, which is meant for producing human-readable expressions in a terminal. If you use InputForm, then it can be convert back to an expression. However, I have to say that trying to manipulate expressions as strings is a very very bad idea. $\endgroup$ – Szabolcs May 30 at 11:09
  • 2
    $\begingroup$ fyi: C1 /. h_[t] :> h $\endgroup$ – Kuba May 30 at 11:25

ToExpression[ToString[x^2, InputForm]] returns the expression that you requested.

It seems that the InputForm parameter in ToString is needed to subsequently use ToExpression.

  • $\begingroup$ Was late with respect to @Szabolcs that gave the more precise answer/comment. $\endgroup$ – DanielAmmering May 30 at 11:18

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