3

I have a list that contents are:

a=['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148\n']

So it contains one member that has numbers in it.

I tried to search for different methods to extract the numbers in float format, as in:

How to remove '\n' from end of strings inside a list?

Remove '\n' from each string stored in a python list

How to remove "\n" in a list of lists (python)

How to remove '\n' from end of strings inside a list?

But their difference with my case is that all of my numbers are inside one '', so once I use

 a=[a[0].strip('\n')]

then the

a[0].split()

this gives me:

['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148']

I can remove the \n, but then I can not extract the numbers in any way. I wanted to split the commas away from the numbers to then remove them one by one, but it seems that split is not working in my case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FabioSpaghetti
  • 790
  • 1
  • 9
  • 35

3 Answers3

4

As lgwilliams mentioned in the comments. You need to specify a delimiter in split otherwise it will default to ' '. In this case you would use split(','). You then need to convert these numbers by casting to float which will, as mhawke mentioned, remove the \n.

With all this in mind you can perform a list comprehension

In [17]: a = ['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148\n']

In [18]: numbers = [float(n) for n in a[0].split(',')]

In [19]: numbers
Out[19]:
[0.00244,
 -0.001908302,
 -0.001731396,
 0.002029896,
 0.000424,
 0.000291,
 0.000148]

You could also use map

In [22]: list(map(float, a[0].split(',')))
Out[22]:
[0.00244,
 -0.001908302,
 -0.001731396,
 0.002029896,
 0.000424,
 0.000291,
 0.000148]
aydow
  • 3,673
  • 2
  • 23
  • 40
2

You can try using regular expression to extract the float values from string and convert to float

list(map(float,re.findall(r'(\-?\d+.\d+)',a[0])))

Out:

[0.00244,
 -0.001908302,
 -0.001731396,
 0.002029896,
 0.000424,
 0.000291,
 0.000148]
Naga kiran
  • 4,528
  • 1
  • 17
  • 31
1

One way to do that would be to split on the commas:

'0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148'.split(',')

Would result in:

['0.00244', '-0.001908302', '-0.001731396', '0.002029896', '0.000424', '0.000291', '0.000148']
Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80