I have hundreds of string that all have the same format -- 2 integers followed by three floats. An example:
1 10 1.2345 5.4321 10.5647
I just want to take these strings one-by-one and parse them into their respective ints and floats. I can think of a few ways to do this, but I was hoping that python would have something elegant, kind of an inverse of the str.format thing that gets used for writing. This seems like very basic functionality, so I'm sorry if I am asking something that has been answered, but I can't find a solution anywhere. Any thoughts? Thanks.
A simple list comprehension should do the trick
>>> mystr = '1 10 1.2345 5.4321 10.5647'
>>> [int(s) if s.isdigit() else float(s) for s in mystr.split()]
[1, 10, 1.2345, 5.4321, 10.5647]
I think you'd be best off with something like numpy's genfromtxt or loadtxt:
import numpy as np
import StringIO
s = """1 10 1.2345 5.4321 10.5647
2 14 434.35 345.34 1000000
3 8 253.235 2.53 .002345"""
f = StringIO.StringIO(s)
data = np.genfromtxt(f, names = 'id, count, x, y, z', dtype=[int,int,float,float,float])
This gives you an array of these things, so the first row is accessible as
data[0]
#(1, 10, 1.2345, 5.4321, 10.5647)
Or all the second column:
data['count']
#array([10, 14, 8])
By the way, this will convert an integer in the float column into a float, in case one of your floats happens to be an integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With