return total value of only strings with a number + dollar

Question:

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
Asked By: Kingmufasa99

||

Answers:

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
Answered By: Juan C

To begin with, you should use the rstrip() method of the string, which removes the character at the end of the string like this:

def is_number(string):
    try:
        float(string.rstrip('$'))
    except:
        return False
    return True

Then, if I understand the 2nd piece of code correctrly (because there are problems with formatting), the result will look like this:

def value_liste(liste):
    amount = 0

    if not liste:
        return 0.0

    for string in liste:
        if isnumber(string):
            amount += float(string.rstrip(('$'))
        return amount

Checking if the list is empty like you did is not idiomatic in Python. Also you can simplify the expression, where you check if the string is a number. If you want a oneliner, you can write:

my_list = ['10$', 'sock', '12.55$', 'pizza11']
total = sum(float(el.rstrip('$')) for el in my_list if el.endswith('$'))
Answered By: spinlock

3 thing to correct here:

  1. As DeepSpace said, the $ disqualifies a string from being interpreted as a float, so it needs to be removed first. The .replace() method is useful here.

  2. Watch your indentation! Python is picky about that. If there is nothing indented after the function is declared, Python will throw an error saying so. Plus, the return statement after the for loop should be at the same level of indentation as the word for; as it is now it just returns the amount after the first iteration, skipping the rest of the list elements.

  3. The conditional in the for loop should include .‘s, so as to include them in the float to include, otherwise your sample list returns 1265.0.

Altogether, here is a corrected version:

def isnumber(string):
    string_no_dollar = string.replace("$", "") # removes all $-signs
    try:
        float(string_no_dollar)
    except:
        return False
    return True


def value_liste(liste):
    # Code is indented after function declaration, as it must always be in Python.
    amount = 0 

    if liste == []:
        return 0.0

    for string in liste:
        if isnumber(string) == True and string[-1:] == '$':
            # Include the "." in the conditional.
            amount += float("".join(d for d in string if d.isdigit() or d == "."))
    # The "return" statement should be indented outside the "for" loop.
    return amount
Answered By: newWorld
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.