-2

I have a list, which was produced as output of a python script in the following format:

[' (* 100.856 UnitA', ') [ 98.0%]',
 ' (* 100.598 UnitB', ') [ 98.0%]', 
 ' (*  98.193 UnitC', ') [ 25.6%]']

Now, I am interested to put the floating point values in every list item to a new list for further processing in a python script. Is there a way (an in-built python function maybe) I can strip the floating point content alone to a new list? In the above example my desired output would be like :

[100.856,98.0,100.598,98.0,98.193,25.6]

If not an in-built function, any other alternate way I can achieve this?

skrowten_hermit
  • 437
  • 3
  • 11
  • 28

1 Answers1

4

Using a regex pattern from here will extract the floats and cast to float as desired:

In [153]:
l=[' (* 100.856 UnitA', ') [ 98.0%]',
 ' (* 100.598 UnitB', ') [ 98.0%]', 
 ' (*  98.193 UnitC', ') [ 25.6%]']
import re
[float(re.findall(r'(-?\d+\.\d+)',x)[0]) for x in l]

Out[153]:
[100.856, 98.0, 100.598, 98.0, 98.193, 25.6]

So the tricky thing here is that you need to search for digits \d but also search for the decimal point and trailing digits

Community
  • 1
  • 1
EdChum
  • 376,765
  • 198
  • 813
  • 562