Reputation: 6651
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.
Upvotes: 3
Views: 2419
Reputation: 103774
You could do something like this:
def linep(line):
line=line.split()
try:
ints=map(int, line[0:2])
floats=map(float, line[2:5])
except ValueError as e:
print e
return ints+floats
print linep('1 10 1.2345 5.4321 10.5647')
Then use it this way:
>>> s='''1 10 1.2345 5.4321 10.5647
-2 11 -0.5 0.5 .3'''
>>> for line in s.splitlines():
... print linep(line)
Prints:
[1, 10, 1.2345, 5.4321, 10.5647]
[-2, 11, -0.5, 0.5, 0.3]
Upvotes: 1
Reputation: 46530
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.
Upvotes: 2
Reputation: 70552
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]
Upvotes: 4