Python: trouble reading number format

▼魔方 西西 提交于 2019-12-13 06:00:41

问题


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.


回答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.




回答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:

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


来源:https://stackoverflow.com/questions/20304939/python-trouble-reading-number-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!