I tried to convert a $\LaTeX$ expression in Mathematica, but it shows me a strange result (it shows a strange word: "ghit").

ToExpression["\\frac{s + k_{12} + k_{02}}
 {V_1 \left[ s^2 + s \left(  k_{12} + k_{02} + k_{21} + k_{01} \r\
ight)  + \left(  k_{21} \, k_{02} + k_{01} \, k_{12} + k_{01} \, \
k_{02} \right) \right] }", TeXForm]

enter image description here

Thank you for your help.

  • $\begingroup$ Shouldn't the single \ be a double \\ ? (You can evaluate the string by itself to see the problem.) $\endgroup$ – Michael E2 Dec 7 '17 at 12:23
  • $\begingroup$ You have to use a backslash \ as escape character for \ (and also for ") when you manipulate strings in Mathematica, exactly as you did in "\\frac{...}". $\endgroup$ – Henrik Schumacher Dec 8 '17 at 21:24

Backslashes, i.e. \, must be escaped in Mathematica strings.

This is incorrect syntax:


The correct syntax is


Unfortunately, Mathematica tries to be "user-friendly" and when using the notebook interface, it accepts "\xyz" without complaint. (If using the terminal, it at least shows a warning.) This creates the false impression that it's fine to do this. It's not. Sequences like \r (which you used), \b, \f, \n, etc. have special meanings. New escape sequences may also be added in the future, breaking code like "\xyz".

Thus: always, always escape backslashes in strings!.

str = "\\frac{s + k_{12} + k_{02}}{V_1 \\left[ s^2 + s \\left(  k_{12} + k_{02} + k_{21} + k_{01} \\right)  + \\left(  k_{21} \\, k_{02} + k_{01} \\, k_{12} + k_{01} \\, k_{02} \\right) \\right] }";

ToExpression[str, TeXForm]

enter image description here

  • $\begingroup$ thank you very much for your excellent solution and explanation! $\endgroup$ – Gennaro Arguzzi Dec 7 '17 at 13:05
  • 1
    $\begingroup$ Is there a way to prevent MMA from dropping the zero in $k_{02}$? $\endgroup$ – Casimir Dec 7 '17 at 13:38
  • 2
    $\begingroup$ @Casimir Good point. I did not notice that. I do not know how to do what you are asking. It is not even about dropping it, but getting it to understand that $0$ and $2$ are two separate numbers. This is a good example of notation that is clear to a human, but not at all to a computer. k_{0,2} would produce a better result. $\endgroup$ – Szabolcs Dec 7 '17 at 13:49
  • 1
    $\begingroup$ @GennaroArguzzi Be aware of the problem pointed out by Casimir above. $\endgroup$ – Szabolcs Dec 7 '17 at 13:49
  • 2
    $\begingroup$ @Casimir You could use k_{\"02\"} instead of k_{02}. $\endgroup$ – Carl Woll Dec 7 '17 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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