Search code examples
pythonlistfiltersum

return total value of only strings with a number + dollar


I need to return the total value of only the strings containing a number+dollar like '12.55$' in ['10$', 'sock', '12.55$', 'pizza11']. This list should return 22.55$ for example (with the dollar sign).

All other string have no value. I created a fuction isnumber:

def isnumber(string):
    try:
        float(string)
    except:
        return False
    return True

And this, but it's not working:

def value_liste(liste):
amount = 0

if liste == []:
    return 0.0

for string in liste:
    if isnumber(string) == True and string[-1:] == '$':
        amount += float("".join(d for d in string if d.isdigit()))
    return amount

Solution

  • This should do:

    l = ['10$', 'sock', '12.55$', 'pizza11']
    answer = str(sum([float(i.replace('$','')) for i in l if i.endswith('$')])) + '$'
    print(answer)
    

    Output:

    22.55$
    

    Step by step:

    • Take only elements from the list that end with '$'
    • Strip '$' from the string and turn it into a float
    • Sum those values.
    • Turn the result into a string.
    • Add '$' at the end of the string