could not convert string to float (python)

后端 未结 2 868
悲哀的现实
悲哀的现实 2021-01-29 14:54

I am trying to find the sum of all numbers in a list but every time I try I get an error that it cannot convert the string to float. Here is what I have so far.

         


        
2条回答
  •  清酒与你
    2021-01-29 15:00

    'elec_used' is of type string of characters. You can not convert characters to the float. I am not sure why you thought you could do it. However you can convert the numeric string to float by typecasting it. For example:

    >>> number_string = '123.5'
    >>> float(number_string)
    123.5
    

    Now coming to your second part, for calculating the sum of number. Let say your are having the string of multiple numbers. Firstly .split() the list, type-cast each item to float and then calculate the sum(). For example:

    >>> number_string = '123.5 345.7 789.4'
    >>> splitted_num_string = number_string.split()
    >>> number_list = [float(num) for num in splitted_num_string]
    >>> sum(number_list)
    1258.6
    

    Which could be written in one line using list comprehension as:

    >>> sum(float(item) for item in number_string.split())
    1258.6
    

    OR, using map() as:

    >>> sum(map(float, number_string.split()))
    1258.6
    

提交回复
热议问题