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?
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.
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.
Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.
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()))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With