-1

python string contains floating point numbers

S = "1,2.5,e,3"

I am trying to convert it to number list by ignoring non-number values.

numbers = ' '.join(c for c in S)

numbers_list = []

for x in numbers:
    if x.isdigit():
        numbers_list.append(x)
print(numbers_list)

Instead of

[1,2.5,3]

it is giving me

['1', '2', '5', '3']

1 Answers1

3
S = "1,2.5,e,3"

numbers = []
for x in S.split(','):
    try:
        numbers.append(float(x))
    except ValueError:
        pass

print(numbers)

Output: [1.0, 2.5, 3.0]

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41