0

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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. stackoverflow.com/questions/1959210/…
Sorry, I initially did it wrong. I'm getting "'int' object has no attribute 'lower'"
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: so don't pass it an int! Read a string from the file, pass it to to_float, and get back a float value.
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
|
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 

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.