unusual exponential formatting puzzle

Neal Becker ndbecker2 at gmail.com
Thu Sep 22 09:14:04 EDT 2005


Paul Rubin wrote:

> Neal Becker <ndbecker2 at gmail.com> writes:
>> Like a puzzle?  I need to interface python output to some strange old
>> program.  It wants to see numbers formatted as:
>> 
>> e.g.: 0.23456789E01
> 
> Yeah, that was normal with FORTRAN.
> 
>> My solution is to print to a string with the '% 16.9E' format, then
>> parse it with re to pick off the pieces and fix it up.  Pretty ugly.
>> Any better ideas?
> 
> That's probably the simplest.

Acutally, I found a good solution using the new decimal module:
def Format(x):
     """Produce strange exponential format with leading 0"""
     s  = '%.9E' % x

     d = decimal.Decimal (s)
     (sign, digits, exp) = d.as_tuple()


     s = ''
     if (sign == 0):
          s += ' '
     else:
          s += '-'

     s += '0.'

     e = len (digits) + exp
     for x in digits:
          s += str (x)
     s += 'E'
     s += '%+03d' % e

     return s





More information about the Python-list mailing list