Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing a python string with floats and ints

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.

like image 247
bob.sacamento Avatar asked Mar 02 '26 03:03

bob.sacamento


2 Answers

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]
like image 141
voithos Avatar answered Mar 04 '26 15:03

voithos


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.

like image 39
askewchan Avatar answered Mar 04 '26 17:03

askewchan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!