Python3: how to add decimals inside a string?

I am starting and I want to add decimal numbers inside string s

  totalsum=0 s='1.23 2.4 3.123' for a in s: totalsum=totalsum+float(a) print (totalsum) 

but when I try he says

 ValueError: could not convert string to float: '.' 

How can I add these three decimal places?

+5
source share
4 answers

you repeat each character of the string. It works first (well, for 1 ...), but when you reach . , you get a parsing error.

Now you need to split the line. And be pythonic, do it on one line:

 totalsum = sum(map(float,s.split())) 
+4
source

You can use regular expressions:

 import re s='1.23 2.4 -4.3 3.123 56' data = sum(map(float, re.findall('(-*\d+\.*\d+)|\b-*\d+\b', s))) 

Output:

 58.453 
+3
source

You have to do this, you are trying to add a whole line to a float. Instead, you need to split and add them

  totalsum=0 s='1.23 2.4 3.123' for a in s.split(): totalsum=totalsum+float(a) print (totalsum) 
+2
source

You need to break the line.

 totalsum=0 s='1.23 2.4 3.123'.split() for a in s: totalsum =totalsum + float(a) print (totalsum) 

output:

 6.753 
+2
source

Source: https://habr.com/ru/post/1272921/


All Articles