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
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: