Home > Mobile >  How do I convert a list of currency strings into float in Python?
How do I convert a list of currency strings into float in Python?

Time:09-02

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. So the output should be:

new_lst = [15700.23, 3000.00, 257.89, 19.50, 36.70]

CodePudding user response:

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)]

CodePudding user response:

you can first use regexp to locate the last period code, and then use str.isdigit() to eliminate irrelevant characters. 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)
  • Related