I am having some trouble setting the width of my output. I have some very long expressions, and I would like to output them as strings of maximum length 80 characters. For example, I have a very long expression "beta" and I would like to output to a file "RGEs_nicks.txt". So I have tried

streamM = OpenWrite["RGEs_nicks.txt", PageWidth -> 80];
WriteString[streamM, ToString[beta // InputForm]];

However, this is not putting in any line breaks, and the output is just one very long line. How do I get this to be formatted output? It works fine if I use just Write instead of WriteString, but I want to be able to add some other tricky stuff before and after so I need the WriteString. Any clues would be much appreciated!

  • $\begingroup$ Probably #<>"\n"&/@StringPartition[ToString[beta // InputForm],UpTo[80]] is what you need? $\endgroup$ – Alx Jul 29 '19 at 10:55
  • $\begingroup$ Thanks @Alx! However, this is not quite what I want, because I think this might break the string into pieces where things should not be split, for example in the middle of a variable. Might this happen? $\endgroup$ – Nick Murphy Jul 29 '19 at 15:34
  • $\begingroup$ Well, this might happen. Another idea: first determine positions of, e.g., spaces: StringPosition[ToString[beta // InputForm], " "]. Then choose from that positions those near to desired length of multiples of 80, and StringInsert[ToString[beta // InputForm], "\n", {<positions>}]. $\endgroup$ – Alx Jul 29 '19 at 16:01
  • $\begingroup$ What tricky stuff causes you to need to use WriteString? $\endgroup$ – Carl Woll Jul 30 '19 at 19:58

Assuming you really need to use WriteString for some reason, you could use ExportString, which respects PageWidth, to do the formatting for you:

streamM = OpenWrite["RGEs_nicks.txt"];
WriteString[streamM, ExportString[beta, "Package", PageWidth -> 80]];

The advantage of using ExportString is that it knows how to preserve a valid syntax when doing the line wrapping, as opposed to blind string splitting.


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.