Skip to content

Instantly share code, notes, and snippets.

@rwest
Created March 31, 2011 20:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rwest/897137 to your computer and use it in GitHub Desktop.
Save rwest/897137 to your computer and use it in GitHub Desktop.
A python function to convert FORTRAN formatted float strings into floats
import re
re_f_float_neg = re.compile('(-?[0-9.]*)(-\d\d\d)')
def fortran_float(input_string):
"""
Return a float of the input string, just like `float(input_string)`,
but allowing for Fortran's string formatting to screw it up when
you have very small numbers (like 0.31674-103 instead of 0.31674E-103 )
"""
try:
fl = float(input_string)
except ValueError,e:
match = re_f_float_neg.match(input_string.strip())
if match:
processed_string = match.group(1)+'E'+match.group(2)
fl = float(processed_string)
else:
print "Trying to find number from ",input_string
raise e
return fl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment