0

Hi i need to split a list that contains string. Some of the strings are words, other are numbers.

I have to float them

x = ['2','45','0.34','4.5','text','wse','56',]

what i tried:

FloatList = [x for x in Mylist if isinstance(x, float)]

but it prints empty list:

[]

Can you point me where am I wrong.

So I need to filter the words from the number strings, float the strings in sep. list

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
George G.
  • 155
  • 1
  • 4
  • 13

1 Answers1

1

These are all string objects, '1.2' isn't 1.2:

>>> type('1.2')
<class 'str'>
>>> type(1.2)
<class 'float'>
>>> 

You should covert them to float object before check.

Since float() function will raise a ValueError if it failed to covert the string that you gives it, you could use try...except to catch that error:

>>> l = []
>>> x = ['2','45','0.34','4.5','text','wse','56'] 
>>> for i in x:
...     try:
...         l.append(float(i))
...     except ValueError:
...         pass

>>> l
[0.34, 4.5, 2, 45, 56]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87