问题描述:

I have data such as:

['$15.50']

['$10.00']

['$15.50']

['$15.50']

['$22.28']

['$50']

['$15.50']

['$10.00']

I want to get rid of the dollar sign and turn the strings into floats so I can use the numbers for several calculations. I have tried the following:

array[0] = float(array.text.strip('$'))

which gives me an attribute error, because apparently a 'list' object has no 'text' attribute. My bad. Is there a similar way for 'list' objects to get stripped? Any other suggestions would be welcome too. Thanks in advance.

网友答案:

Try using a list comprehension:

array = [float(x.strip("$")) for x in array]
网友答案:

With regex:

import re
array = ([float(re.sub("\$","",x)) for x in array])

In case '$' is not at the end or beginning of the string

网友答案:

This should do:

[float(s.replace(',', '.').replace('$', '')) for s in array]

I have taken the liberty to change your data in order to consider a wider variety of test cases:

array = ['$15.50',
         '$ 10.00',
         '  $15.50  ',
         '$15,50',
         '$22,28 ',
         '  10,00  $  ']

And this is what you get:

In [8]: [float(s.replace(',', '.').replace('$', '')) for s in array]
Out[8]: [15.5, 10.0, 15.5, 15.5, 22.28, 10.0]
相关阅读:
Top