How to convert TableForm to proper LaTex and why is “\” not replaced by StringReplace?

I’m trying to optimize the teXForm output of a table because the standard output ist not satisfying:

badLatex = TeXForm[TableForm[{
{“nm”, “E1”, “E2”},
{500.`, -0.001`, -0.001`},
{499.`, -0.001`, 0.`},
{498.`, 0.`, -0.001`}}]]

I get this output

\begin{array}{ccc}
\text{nm} & \text{E} & \text{E} \\
500. & -0.001 & -0.001 \\
499. & -0.001 & 0. \\
498. & 0. & -0.001 \\
\end{array}

No I want to replace the decimal points with commas, change the environment and eliminate the “\text” command. The last doesn’t work for me.

goodLatex = StringReplace[ToString[badLatex],
{“array” -> “tabular”,”.” -> “,” , “\text” -> “”}]

I get the following result:

\begin{tabular}{ccc}
\text{nm} & \text{E1} & \text{E2} \\
500, & -0,001 & -0,001 \\
499, & -0,001 & 0, \\
498, & 0, & -0,001 \\
\end{tabular}

As you can see, the expression “\text” is still there. Why is “\” not replaced by StringReplace?
Do you have a better idea how to convert tables to proper LaTex code?

Thanks in advance for your help!
Michael

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

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

2 Answers
2

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

In Mathematica, as well as many other programming languages (C, Java, Python, etc.), a two-character sequence of the form \x, where x may be anything, represents a single character in the string. This is just a notational convention that allows us to enter characters that would otherwise be impossible to include in a string. This notation is called escape sequences.

Examples: “\”” is a single character string containing “. The -notation makes it possible to include a ” sign in a string delimited using the same character. Other common escape sequences: “\n” is a newline, “\r” is a carriage return, “\t” is a tab, etc.

To enter a string containing \, you need to use the notation “\\”. So your StringReplace will need to have “\\text” -> “”.

In Mathematica strings \ is an escape character. Try:

StringReplace[ToString[badLatex], {“array” -> “tabular”, “.” -> “,”, “\\text” -> “”}]

Also, you say “proper LaTeX code” but the original “badLatex” string is recognized here as:

nmE1E2500.−0.001−0.001499.−0.0010.498.0.−0.001nm500.499.498.E1−0.001−0.0010.E2−0.0010.−0.001\begin{array}{ccc}
\text{nm} & \text{E1} & \text{E2} \\
500. & -0.001 & -0.001 \\
499. & -0.001 & 0. \\
498. & 0. & -0.001
\end{array}

which seems alright to me.