How to remove strings that contain letters from a list?

115 views Asked by At

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.

2

There are 2 answers

0
tobias_k On BEST ANSWER

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.

1
Anand S Kumar On

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))