Converting a string (with scientific notation) to an int in Python

后端 未结 2 2024
忘了有多久
忘了有多久 2020-12-03 17:56

I\'m trying to convert a set of strings from a txt file into int\'s within a list. I was able to find a nice snippet of code that returns each line and then I proceeded to t

相关标签:
2条回答
  • 2020-12-03 18:19

    Use float(i) or decimal.Decimal(i) for floating point numbers, depending on how important maintaining precision is to you.
    float will store the numbers in machine-precision IEEE floating point, while Decimal will maintain full accuracy, at the cost of being slower.
    Also, you can iterate over an open file, you don't need to use readlines().
    And a single list comprehension can do everything you need:

    data = [float(number)
            for line in open('data.txt', 'r')
            for number in line.split()]
    

    If you really only need integers, you can use int(float(number))

    0 讨论(0)
  • 2020-12-03 18:33

    Your string looks like a float, so convert it to a float first.

    0 讨论(0)
提交回复
热议问题