python - How to remove strings that contain letters from a list? -
i have list containing strings both letters, characters , and numbers:
list = ['hello', '2u:', '-224.3', '45.1', 'sa 2']
i want keep numbers in list , convert them float
values. how can that? want list this:
list = ['-224.3'. '45.1']
the list created, when serial.readline() arduino, gives me string comprised of commands , data points. looked this:
'hello,2u:,-224.3,45.1,sa 2'
i did list.split(delimiter=',') , wanted have data points future calculations.
probably best way see whether string can cast float
try
cast it.
res = [] x in lst: try: res.append(float(x)) except valueerror: pass
afterwards, res
[-224.3, 45.1]
you could make list comprehension, [float(x) x in lst if is_float(x)]
, need function is_float
same thing: try cast float , return true, otherwise return false. if need once, loop shorter.
Comments
Post a Comment