Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of a string contains a sequence of decimal numbers [closed]

I'm really a starter in programming. I want to prints the sum of a string s = '1.23,2.4,3.123'. I tried to use

total = 0.0
for s in '1.23,2.4,3.123':
    total += float(s)
print total

but it doesn't work, could anyone help? THX a lot

like image 321
user2321868 Avatar asked Oct 22 '25 04:10

user2321868


1 Answers

You could try the following:

total = sum(float(i) for i in s.split(','))

It runs like this:

  • s.split(',') pulls out each 'number' in the string

  • float(i) for i in s... makes a float of each split value

  • sum() adds them all up

Hope this helps!

like image 118
Nick Burns Avatar answered Oct 24 '25 14:10

Nick Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!