-3

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.

  • What do you want to happen to elements that contain both numbers and letters? Should the letters be stripped out and the number portion returned, or should the whole element be thrown out? I.e. does '2U:' return 2 or is it excluded from the results entirely? – Seth Jun 10 '15 at 14:24
  • Have a look at [this](https://stackoverflow.com/questions/30238598/python-how-to-separate-list-based-on-numerical-values-and-strings-from-a-given) question it seems to be very similar to yours. – Tom Jun 10 '15 at 14:35
  • @EpsilonX The difference is: In that other question, the numbers are _actual_ numbers, thus all the answers use some sort of `isinstance` for testing. This won't work here. – tobias_k Jun 10 '15 at 14:37
  • @jonrsharpe, I was reading lines from a serial port, which contained both command lines and actual data. The resultant readline, gave me a long string, which I split up into list elements. Since I only needed specific lines, I wanted to remove anything that wasn't data – Jacob Hermann Olesen Jun 11 '15 at 12:37
  • That doesn't answer my question: where's the *code*? See http://stackoverflow.com/help/mcve – jonrsharpe Jun 11 '15 at 12:41

2 Answers2

2

Probably the best way to see whether a string can be cast to float is to just try to cast it.

res = []
for x in lst:
    try:
        res.append(float(x))
    except ValueError:
        pass

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 function is_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.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

You can try something like below -

def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
bools = list(map(lst,isNum))
deleted = 0
for idx, val in enumerate(bools):
    if val:
            continue
    else:
            del lst[idx-deleted]
            deleted = deleted + 1

EDIT:

Or you can use

def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
lst = list(filter(isNum, lst))
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176