I am reading from a file where numbers are listed as -4.8416932597054D-04, where D is scientific notation. I have never seen this notation before. How can Python read -4.8416932597054*D*-04 as -4.8416932597054*E*-04 I've looked at other question and haven't read anything that addresses this? (Or I have and didn't recognize it.) Thanks.
Asked
Active
Viewed 272 times
2 Answers
1
def to_float(s):
return float(s.lower().replace('d', 'e'))
Edit: Can you give an example of an input string that still gives you 'the same error'? Because to_float('-4.8416932597054D-04')
works perfectly for me, returning -0.00048416932597054
.

Hugh Bothwell
- 55,315
- 8
- 84
- 99
-
I'm still getting the same error. I just found other discussions identify D as FORTRAN scientific notation and numpy as FORTRAN-friendly. I've already imported numpy for other purposes, so perhaps there is a way there. http://stackoverflow.com/questions/1959210/python-scientific-notation-using-d-instead-of-e – user3052914 Nov 30 '13 at 20:26
-
Sorry, I initially did it wrong. I'm getting "'int' object has no attribute 'lower'" – user3052914 Nov 30 '13 at 21:07
-
I should also add that I will use the function to read elements in an array. For example, to_float(col_C), col_C being a 1D array read from a text file. – user3052914 Nov 30 '13 at 21:21
-
@user3052914: so don't pass it an int! Read a string from the file, pass it to to_float, and get back a float value. – Hugh Bothwell Nov 30 '13 at 21:21
-
def to_float(s): ----> 2 return float(s.lower().replace('d', 'e')) 3 4 col_C='-4.8416932597054D-04' 5 ValueError: could not convert string to float: col_c – user3052914 Nov 30 '13 at 21:44
-
Pardon the last comment. I got a ValueError: could not convert string to float. I need to go back to where I read in these column and format them as strings; then it should work. Thank you for your help. – user3052914 Nov 30 '13 at 21:57
0
Do you understand this notation? If so, you can use your knowledge to solve that. Do string formatting with the number, parse it, extract D-04
from the number using regular expressions and translate it into a more numberish string, append to the original string and make Python convert it.
There's not a Python module for every case or every data model in the world, we (you, especially) have to create your own solutions.
Example:
def read_strange_notation(strange_number):
number, notation = strange_number.split('D-')
number, notation = int(number), int(notation)
actual_number = number ** notation # here I don't know what `D-` means,
# so you do something with these parts
return actual_number

fiatjaf
- 11,479
- 5
- 56
- 72
-
I do understand the notation- now. I, however, do not know how to parse, extract, translate and append it. Could you help me with that? – user3052914 Nov 30 '13 at 20:53