Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 try and convert it to an int. The problem is that the numbers are in scientific notation and I get this error: ValueError: invalid literal for int() with base 10: '3.404788e-001'.

This is the code I've been messing around with

data = []
rawText = open ("data.txt","r")

for line in rawText.readlines():
    for i in line.split():
        data.append(int(i))

print data[1]
rawText.close()
like image 437
DamianJ Avatar asked Feb 18 '12 04:02

DamianJ


2 Answers

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))

like image 114
tzaman Avatar answered Sep 21 '22 01:09

tzaman


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

like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 01:09

Ignacio Vazquez-Abrams