specify field width in Print

I would like to format the output. For example, the following code gives

For[n=2,n<=10,n++,
factorization =FactorInteger[n];
length=Length[factorization];
If[length==1,
factorization =(Superscript@@@FactorInteger[n])[[1]],
factorization =CenterDot@@(Superscript@@@FactorInteger[n])
];

Print["n = ", n, " = ", factorization, ", number of prime factors = ", length];
]


But what I want is something similar to the following (but better alignment)

I know there is Grid, but I don't know how to use them in this current case. Also, I prefer a simpler solution (if there is), such as one can specify a "field width" like in the C language.

• How about a different approach using Grid? Layout-wise, this will be much more comfortable and powerful. – Yves Klett Feb 14 '14 at 10:53
• ... hijacking your code: Reap[For[n = 2, n <= 10, n++, factorization = FactorInteger[n]; length = Length[factorization]; If[length == 1, factorization = (Superscript @@@ FactorInteger[n])[[1]], factorization = CenterDot @@ (Superscript @@@ FactorInteger[n])]; Sow[{"n = ", n, " = ", factorization, "; number of prime factors = ", length}];]][[2, 1]] // Grid – Yves Klett Feb 14 '14 at 10:55
• I really need to understand Reap/Sow :P – Öskå Feb 14 '14 at 10:56
• @YvesKlett: Great. I didn't know how to use Grid because I used Print[]. Thanks – user565739 Feb 14 '14 at 10:57
• I would encourage you to change your username into something more unique, which simplifies the interaction and enhances the overall community experience :D – Yves Klett Feb 14 '14 at 12:41

Grid is really quite useful for things like that if you can provide a finished list with results.

In this case I was to lazy to replace your procedural code (e.g. with Table) and just extracted the data you would have printed with Sow and Reap:

data = Reap[For[n = 2, n <= 10, n++, factorization = FactorInteger[n];
length = Length[factorization];
If[length == 1,
factorization = (Superscript @@@ FactorInteger[n])[[1]],
factorization = CenterDot @@ (Superscript @@@ FactorInteger[n])];
Sow[{"n = ", n, " = ", factorization,
"; number of prime factors = ", length}];]][[2, 1]];

Grid[data]


Now you can start playing around with Grid options to get a format of your liking.

Supposing you want to print from inside the loop (not waiting for the loop to finish) you can use Grid on each line with specified field widths:

 Do[
Print@Grid[{{
RandomChoice[DictionaryLookup["*"]], "=",
RandomReal[{1, 10}]^RandomInteger[12]}},
ItemSize -> {{10, Full, 8}},
Alignment -> {{Right, Center, Right}}],
{10}]


Another approach for nicely formatted monitoring..

out = {};
Monitor[
Do[  Pause[1];
AppendTo[out, {RandomChoice[DictionaryLookup["*"]], "=",
RandomReal[{1, 10}]^RandomInteger[12]}],
{10}],
Grid[out, Alignment -> {Right, Center, Right}]]

• Good point about using fixed widths anyway! – Yves Klett Feb 15 '14 at 16:04