I want to sum only number in list , my list contain also characters what is best way? I try this
x = ['0.1₾', '0.1₾', '2₾', '0.2₾', '0.2₾', '0.2₾', '0.2₾', '0.2₾', '0.2₾', '5₾', '2₾', '9.9₾', '0.7₾', '5₾', '0.9₾', '0.8₾', '0.2₾', '1₾', '0.2₾', '3₾', '0.3₾', '5₾', '0.1₾', '2₾', '0.8₾', '1₾'] y = 0 for i in x: y += float(i) print(y)
but error:
ValueError: could not convert string to float: '0.1₾'
what is best solution ?`
Advertisement
Answer
Since the character always appears as the last character in every element in the array, you can use the substring method to isolate the float part of each element
All you would need to change in your code is instead of:
y += float(i)
use:
y += float((i[0:len(i) - 1]))
If you want to use negative indexing:
y += float((i[0:-1]))
Either of the options above work :)