Skip to content Skip to sidebar Skip to footer

Python: Trouble Reading Number Format

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.84169325

Solution 1:

defto_float(s):
    returnfloat(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.

Solution 2:

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:

defread_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 partsreturn actual_number

Post a Comment for "Python: Trouble Reading Number Format"