This works. It returns "acb".

StringForm["a``b", "c"]

This doesn't work.

Export["test.txt", StringForm["a``b", "c"]]

Rather than "acb", test.txt contains the literal expression StringForm["a``b", "c"].

This doesn't work either - it's the same result.

Export["test.txt", Evaluate[StringForm["a``b", "c"]]]

How can I force Mathematica to perform the StringForm?

  • 2
    $\begingroup$ Could try Export["test.txt", ToString @ StringForm["a``b", "c"]], but things will get ugly very quickly if the second argument of StringForm has things like 1/2 or 1.2*^-6. $\endgroup$
    – Carl Woll
    Sep 20, 2021 at 23:56
  • $\begingroup$ I think StringTemplate is a better choice in this case. $\endgroup$
    – xzczd
    Sep 21, 2021 at 2:22
  • $\begingroup$ @xzczd I personally don't like StringTemplate, e.g., things like StringTemplate["first `a` then `b`"][<|"a"->1/2, "b"->1.2*^-77|>] produce output that I consider very suboptimal. $\endgroup$
    – Carl Woll
    Sep 21, 2021 at 4:32
  • $\begingroup$ @carl-woll Thanks for the suggestion! Unfortunately, ToString[StringForm[a,b]] seems to behave very strangely if b contains newlines (which my use case does). E.g. I'd expect ToString[StringForm["AAA``BBB", "CCC\nDDD"]] to return "AAACCC\nDDDBBB", but it actually returns "AAACCCBBB\n\ \ \ DDD". (Wrong letter order, extra whitespace.) StringForm["AAA``BBB", "CCC\nDDD"] alone behaves as expected. $\endgroup$
    – ppm
    Sep 21, 2021 at 20:06
  • 1
    $\begingroup$ @ppm That's the same issue as I mentioned with 1/2 or 1.2*^-6. If you are only dealing with strings, then you can do: First@ToBoxes@StringForm["AAA``BBB", "CCC\nDDD"] $\endgroup$
    – Carl Woll
    Sep 21, 2021 at 20:27


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.

Browse other questions tagged or ask your own question.