# How to get output in a specified format

In Fortran, we can easily get the stardard and easy output format. Now, we only focus on the Integer output. See here How to realize this kind of output as formatted text file using Mathematica ? (Then it can be read in Fortran easily).Take a simple example, I have a list,

   list=Table[(i + j) i (i - j), {i, 1, 2}, {j, 1, 22}];


I want to get the output data in a text file and

1. Every integer should be printed with 6 positions. (It is I6 in Fortran).
2. The maximum line length in the text file should be limited to 120.

• Your question is not clear. Is your goal to format output in a Mathematica notebook, or is it exporting your data to disk as formatted text? – m_goldberg Mar 24 '15 at 3:08
• To obtain the formatted text file. – Orders Mar 24 '15 at 3:10
• OK, but in a file or on the screen in a notebook window? – m_goldberg Mar 24 '15 at 3:12
• The output should be stored in a text file. – Orders Mar 24 '15 at 3:22
• Is the maximum line length something you are supplying and is represented in the actual file, e.g. -399\n -440, or were you just saying that's how the file would look in an editor whose maximum line length is set to 120. – Andrew Cheong Mar 24 '15 at 3:24

data = Table[(i + j) i (i - j), {i, 1, 2}, {j, 1, 22}];


The first step is to define a function to break up each row in the data into lines not exceeded the specified maximum line length.

prep[row_, fieldWidth_, lineLength_] :=
Module[{items = Floor[lineLength/fieldWidth]},
Partition[row, items, items, 1, {}]]


The second step is to do the breaking. I have shorten the lines to 80 characters for better looking output to show here.

lines = Flatten[prep[#, 6, 80] & /@ data, 1];


The third step is to make the strings

output =
StringJoin @@@
Map[StringTake[StringJoin["     ", ToString@#], -6] &, lines, {2}]


The final step is to export the strings. I use ExportString for demonstration.

ExportString[output, "Text"]


You can use something similar to

Export["~/Desktop/test.txt", output, "Text"]


to put the strings into a disk file.

### Update

As suggested by SjoerdC.deVries in a comment,

output =
StringJoin @@@
Map[ToString[NumberForm[#, 6, NumberPadding -> " "]] &, lines, {2}];


is an alternative way to make the strings.

• How about IntegerString? – Sjoerd C. de Vries Mar 24 '15 at 6:32
• @SjoerdC.deVries. Not sure what you are getting at, but consider that IntegerString[-42, 10, 6] gives "000042". To munge that into the form I actually need doesn't seem better than what I did. – m_goldberg Mar 24 '15 at 14:13
• OK, that was too quick. How about NumberForm[-42, 6, NumberPadding -> " "] // ToString then? – Sjoerd C. de Vries Mar 24 '15 at 14:17
• @SjoerdC.deVries. That'a good idea. I added an update giving it as an alternative. – m_goldberg Mar 25 '15 at 4:56