Skip to content
Advertisement

Removing all commas from list in Python

My issue: I’d like to add all the digits in this string '1.14,2.14,3.14,4.14' but the commas are causing my sum function to not work correctly.
I figured using a strip function would solve my issue but it seems as though there is still something I’m missing or not quite understanding.

total = 0
for c in '1.14,2.14,3.14'.strip(","):
    total = total + float(c)
print total

I have searched how to remove commas from a string but I only found information on how to remove commas from the beginning or ending of a string.

Additional Info: Python 2.7

Advertisement

Answer

I would use the following:

# Get an array of numbers
numbers = map(float, '1,2,3,4'.split(','))

# Now get the sum
total = sum(numbers)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement