A little algorithm that converts numbers to a character string and then adds it is:
total= 0
cadena= "1.2,1.5,1.7"
for i in cadena.split(","):
i= float(i)
total+= i
print(total)
Now, suppose that the numbers come individually in quotes like this:
cadena= "1.2","1.5","1.7"
What is the command that I must use so that each number remains as a float and then add it using the same for? Using the initial code for the last string I get the following error:
AttributeError: 'tuple' object has no attribute 'split'
Any guidance will be greatly appreciated.
cadena = "1.2","1.5","1.7"
is a tuple actually, it is equivalent tocadena = ("1.2","1.5","1.7")
. Simply loop through it with afor
and do the casting:If you want a tuple of floats use a compression generator:
Here are two approaches to achieve the same thing:
whose result is: