I am starting and I want to add decimal numbers inside string s
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?
you repeat each character of the string. It works first (well, for 1 ...), but when you reach . , you get a parsing error.
1
.
Now you need to split the line. And be pythonic, do it on 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
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)
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
Source: https://habr.com/ru/post/1272921/More articles:Trigger SMS via SOA / UMS does not receive the sender address from the sdpmessagingdriver-smpp driver configuration settings - oracleButterknife gradle error on Android Studio 3.0 due to android-apt plugin - androidAndroid Studio 3 does not run tests in Spock - android-studioC ++ How to assign ifstream content (from a file) to a line with an offset (istreambuf_iterator) - c ++Retrieving a string resource from another application - androidjQuery writing iframe in XLS causes sandbox violation on iPhone - javascriptQt5 QWidget: freezing effect hang - c ++Android Studio error ": could not read metadata" after updating to 3.0.0 - androidExactly what quantifiers require SMT? - smtRedirectIfAuthenticated redirect if trying to open another login form - phpAll Articles