Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3: How can I add decimals that are inside a string

I am a beginner and I want to add the decimals inside the 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 it says

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

How can I add those three decimals?

like image 432
huhu julu Avatar asked Oct 26 '17 16:10

huhu julu


People also ask

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

How do I format a string as a decimal in Python?

To format decimals, we will use str. format(number) where a string is '{0:. 3g}' and it will format string with a number. Also, it will display the number with 1 number before the decimal and up to 2 numbers after the decimal.

How do you add decimal precision in Python?

Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.


2 Answers

you're iterating on every character of the string. It works at first (well, for 1...), but when you reach . you get a parse error.

Now, you need to split your string. And be pythonic, do that in one line:

totalsum = sum(map(float,s.split()))
like image 190
Jean-François Fabre Avatar answered Oct 16 '22 08:10

Jean-François Fabre


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
like image 29
Ajax1234 Avatar answered Oct 16 '22 10:10

Ajax1234