[英]How do I convert a list of currency strings into float in Python?
I have a list like this:我有一个这样的列表:
lst = ['$15,700.23', '3,000', '257.89', '19. 50', '$36.7', '36.2.13', 'abc23.50']
How do I convert it into a list of floats without the '$'
, ','
and whitespace,if it contains anyother special symbols(or like '36.2.13') delete it from the list.如果它包含任何其他特殊符号(或像 '36.2.13'),如何将其转换为不带
'$'
、 ','
和空格的浮点数列表,将其从列表中删除。 So the output should be:所以 output 应该是:
new_lst = [15700.23, 3000.00, 257.89, 19.50, 36.70]
just fix the string like that:只需像这样修复字符串:
from collections import Counter
strings = [w.replace('$',"").replace(',',"").replace(" ","") for w in lst]
def is_floatable(strng):
try:
float(strng)
return True
except:
return False
new_lst = [float(w) for w in strings if is_floatable(w)]
you can first use regexp to locate the last period code, and then use str.isdigit()
to eliminate irrelevant characters.您可以先使用正则表达式定位最后一个句点代码,然后使用
str.isdigit()
消除不相关的字符。 See if this matches your expectations.看看这是否符合您的期望。
import re
lst = ['$15,700.23', '3,000', '257.89', '19. 50', '$36.7', '36.2.13', 'abc23.50']
def clean_number(s):
if '.' in s:
ints,decimals = re.match('(.+)\.(.+)',s).groups()
else:
ints = s
decimals = '0'
int_part = ''.join((s for s in ints if s.isdigit()))
decimal_part = ''.join((s for s in decimals if s.isdigit()))
return float(f'{int_part}.{decimal_part}')
list_cleaned = [clean_number(s) for s in lst]
print(list_cleaned)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.