简体   繁体   English

如何在 Python 中将货币字符串列表转换为浮点数?

[英]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.

相关问题 如何将字符串和数字列表转换为在 python 中浮动? - How to convert a list of strings and numbers to float in python? 如何修改字符串的python数组以去除所有字母数字,转换为float,然后将float存储在同一数组中? - How do I modify a python array of strings to strip any alphanumerics, convert to float, and then store the float in the same array? 如何在Python中将字符串列表转换为整数? - How do I convert a list of strings to integers in Python? 在Python中,如何将int和字符串列表转换为Unicode? - In Python, how do I convert a list of ints and strings to Unicode? 如何将嵌套列表转换为浮点数? - How do I convert a nested list into a float? 如何将字符串列表转换为浮点数数组? - How can I convert a list of strings to an array of float numbers? 在pandas中,如何将一系列float或none转换为带整数的字符串 - In pandas, how do I convert a series of float or none to strings with integers 如何在 Python 中将货币字符串转换为浮点数? - How do I convert a currency string to a floating point number in Python? 如何将所有字符串(如“故障”)转换为唯一的浮点数? - How do I convert all strings (like “Fault”) and into a unique float? 如何将字符串列表转换为字典? - How do I convert a list of strings to a dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM