7
$\begingroup$

I want to compose a string that contains newlines, so I tried the following:

ToString@StringForm["SomeText='`1`'\[NewLine]as well as OtherText='`2`'.", "textA", "textB"]

I would expect this to produce a string that looked like:

SomeText='textA'
as well as OtherText='textB'

Instead, I get a string that looks like

SomeText='textA'                      textB'.
                as well as OtherText='

Directly entering the string "SomeText='textA'\[NewLine]as well as OtherText='textB'" gives me the correct result.

What is going on here?

$\endgroup$
1

1 Answer 1

6
$\begingroup$

I ran into this problem in 2009. I submitted it to WRI technical support. This is the reply I received.

After going through your notebook, I believe that what you observed is the expected behavior of ToString. To elaborate:

When you use ToString[form], ToString prints out the string in the OutputForm. Further this function to put everything sequentially and therefore does not recognize that ALL the strings after \n should be placed in a different line. Rather it just puts the string directly associated with \n\n two spaces down and then resumes printing the later strings in the same line.

The simplest way that you can remedy this issue is to use

ToString[form,TraditionalForm]

or

ToString[form, StandardForm]

both these options retain the original intended format.

Following this advice will give output that looks the way you want, but it may not be what you really want because it is not a simple string, but an interpretation box.

str = ToString[
  StringForm["SomeText='`1`'\nas well as OtherText='`2`'.", "textA", "textB"], 
  StandardForm]
SomeText='textA'
as well as OtherText='textB'.
str // FullForm

fullform.png

After receiving tech support's reply, I thought I might work around this by using Row instead of StringForm, but that didn't work. It gives the same output as you got with StringForm because, as the tech support reply implies, the problem lies in how ToString works and not with StringForm.

If you really want a simple string, I'm afraid you will have use Mathematica's string manipulation tools to build the string from component parts.

$\endgroup$
1
  • $\begingroup$ Ah! That makes a little more sense... Thanks for the help. $\endgroup$
    – Daniel
    Jan 8, 2014 at 0:29

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.