开发者

convert string into int()

I have a dataset that looks like this:

0 _ _ 23.0186E-03  
10 _ _51.283E-03  
20 _ _125.573E-03

where the numbers are lined up line by line (the underscores represent spaces).

The numbers in the right hand column are currently part of the line's string. I am trying to convert the numbers on the right into numerical values (0.0230186 etc). I can convert them with int() once they are in a simple numerical form, but I need to change the "E"s to get there. If you know how to change it for any value of E such as E-01, E-22 it would be very helpful.

Currently my code looks like so:

fin = 开发者_高级运维open( 'stringtest1.txt', "r" )  
fout = open("stringtest2.txt", "w")

while 1:  
    x=fin.readline()

    a=x[5:-1]  
    ##conversion code should go here

    if not x:
        break

    fin.close()  
    fout.close()


I would suggest the following for the conversion:

float(x.split()[-1])

str.split() will split on white space when no arguments are provided, and float() will convert the string into a number, for example:

>>> '20  125.573E-03'.split()
['20', '125.573E-03']
>>> float('20  125.573E-03'.split()[-1])
0.12557299999999999


You should use context handlers, and file handles are iterable:

with open('test1.txt') as fhi, open('test2.txt', 'w') as fho:
  for line in fhi:
    f = float(line.split()[-1])

    fho.write(str(f))


If I understand what you want to do correctly, there's no need to do anything with the E's: in python float('23.0186E-03') returns 0.0230186, which I think is what you want.

All you need is:

fout = open("stringtest2.txt", "w")
for line in open('stringtest1.txt', "r"):
    x = float(line.strip().split()[1])
    fout.write("%f\n"%x)
fout.close()

Using %f in the output string will make sure the output will be in decimal notation (no E's). If you just use str(x), you may get E's in the output depending on the original value, so the correct conversion method depends on which output you want:

>>> str(float('23.0186E-06'))
'2.30186e-05'
>>> "%f"%float('23.0186E-06')
'0.000023'
>>> "%.10f"%float('23.0186E-06')
'0.0000230186'

You can add any number to %f to specify the precision. For more about string formatting with %, see http://rgruet.free.fr/PQR26/PQR2.6.html#stringMethods (scroll down to the "String formatting with the % operator" section).


float("20 _ _125.573E-03".split()[-1].strip("_"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜