title: Decimal alignment formatting in Python
body: <p>This <em>should</em> be easy.</p>
  
  <p>Here's my array (rather, a method of generating representative test arrays):</p>
  
  <pre><code>&gt;&gt;&gt; ri = numpy.random.randint
  &gt;&gt;&gt; ri2 = lambda x: ''.join(ri(0,9,x).astype('S'))
  &gt;&gt;&gt; a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))])
  &gt;&gt;&gt; a
  array([  7.99914000e+01,   2.08000000e+01,   3.94000000e+02,
           4.66100000e+03,   5.00000000e+00,   1.72575100e+03,
           3.91500000e+02,   1.90610000e+04,   1.16247000e+04,
           3.53920000e+02])
  </code></pre>
  
  <p>I want a list of strings where '\n'.join(list_o_strings) would print:</p>
  
  <pre><code>   79.9914
     20.8
    394.0
   4661.0
      5.0
   1725.751
    391.5
  19061.0
  11624.7
    353.92
  </code></pre>
  
  <p>I want to space pad to the left <em>and</em> the right (but no more than necessary).</p>
  
  <p>I want a zero after the decimal if that is all that is after the decimal.</p>
  
  <p>I do not want scientific notation.</p>
  
  <p>..and I do not want to lose any significant digits.  (in 353.98000000000002 the 2 is not significant)</p>
  
  <p>Yeah, it's nice to want..</p>
  
  <p>Python 2.5's <code>%g, %fx.x</code>, etc. are either befuddling me, or can't do it.
  I have not tried <code>import decimal</code> yet.  I can't see that <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> does it either (although, the <code>array.__str__</code> and <code>array.__repr__</code> are decimal aligned (but sometimes return scientific).</p>
  
  <p>Oh, and speed counts.  I'm dealing with big arrays here.</p>
  
  <p>My current solution approaches are:</p>
  
  <ol>
  <li>to str(a) and parse off NumPy's brackets</li>
  <li>to str(e) each element in the array and split('.') then pad and reconstruct</li>
  <li>to a.astype('S'+str(i)) where i is the max(len(str(a))), then pad</li>
  </ol>
  
  <p>It seems like there should be some off-the-shelf solution out there... (but not required)</p>
  
  <p>Top suggestion fails with when <code>dtype</code> is float64:</p>
  
  <pre><code>&gt;&gt;&gt; a
  array([  5.50056103e+02,   6.77383566e+03,   6.01001513e+05,
           3.55425142e+08,   7.07254875e+05,   8.83174744e+02,
           8.22320510e+01,   4.25076609e+08,   6.28662635e+07,
           1.56503068e+02])
  &gt;&gt;&gt; ut0 = re.compile(r'(\d)0+$')
  &gt;&gt;&gt; thelist = [ut0.sub(r'\1', "%12f" % x) for x in a]
  &gt;&gt;&gt; print '\n'.join(thelist)
    550.056103
   6773.835663
  601001.513
  355425141.8471
  707254.875038
    883.174744
     82.232051
  425076608.7676
  62866263.55
    156.503068
  </code></pre>