-2

I am trying to take an input from a "raw_input" function and make it into 3 floats and then sum them up.

user_input = "1.23+2.25+3.25"

is it possible to take the 3 numbers and add them to a list of floats that look like this or something similar?

float_lst = [1.23,2.25,3.25]

3 Answers3

1

Yes.

float_lst = [float(i) for i in user_input.split("+")]
LiranT
  • 91
  • 6
0

If I only go by your requirement, not the list, you can eval. Trivial code example below

a = raw_input()
print eval(a)
kmcodes
  • 807
  • 1
  • 8
  • 20
  • 1
    Nice solution, but it is usually not a good idea to eval user input. If you don't "trust" the input you can use [ast.literal_eval](https://docs.python.org/3/library/ast.html#ast.literal_eval) to safely evaluate input. – Hirabayashi Taro Nov 24 '17 at 12:58
  • Thats true. Mea culpa. – kmcodes Nov 24 '17 at 13:13
0

You can use the split function and then cast the elements to float.

user_input = "1.23+2.25+3.25"
lst = user_input.split("+")
lst = [float(i) for i in lst]

Now you have a list of float so you can do

result = sum(lst)

And you will have the result

PrisonGuy
  • 15
  • 4