Extracting float from string
Don Arnold
dlarnold at west.com
Wed Jan 15 15:21:07 EST 2003
Spencer Ernest Doidge <spencer at efn.org> wrote in message news:<avvp7s$l1i$1 at news.efn.org>...
> From a previous post,
> I got many good solutions to extracting an int from
> 'X= 445 A'.
>
> Now what about this one?
> Somewhere (we don't know where) in this input string, we expect to find a float:
> ':X= 0.22456 A'
>
> How can I suck the float out of this one?
This isn't all that pretty, but appears to work:
str = ':X= 0.22456 A 423 12.345 a.b'
for item in [x for x in str.split()]:
try:
float(item)
if item.find('.') != -1:
print '%s is a float' % item
else:
print '%s is not a float but can be converted to one' % item
except:
print '%s is not a float' % item
>>>
:X= is not a float
0.22456 is a float
A is not a float
423 is not a float but can be converted to one
12.345 is a float
a.b is not a float
>>>
HTH,
Don
More information about the Python-list
mailing list