I have a list containing strings with both letters, characters and and numbers:
list = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
I want to only keep the numbers in a list and convert them to float
values. How can I do that? I want the list to look like this:
list = ['-224.3'. '45.1']
The list is created, when I do a serial.readline() from a Arduino, which gives me a string comprised of commands and data points. So i looked like this:
'hello,2U:,-224.3,45.1,SA 2'
I did a list.split(delimiter=',') and wanted to only have the data points for future calculations.
Probably the best way to see whether a string can be cast to
float
is to justtry
to cast it.Afterwards,
res
is[-224.3, 45.1]
You could also make this a list comprehension, something like
[float(x) for x in lst if is_float(x)]
, but for this you will need a functionis_float
that will essentially do the same thing: Try to cast it as float and return True, otherwise return False. If you need this just once, the loop is shorter.