3
$\begingroup$

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

$\endgroup$

2 Answers 2

5
$\begingroup$

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" -> "".

$\endgroup$
2
$\begingroup$

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:

$\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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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