How to add the result that is inside the Split function in python?

2

Input value: 6+5

Example: Within the variable data are the numbers ['6', '5'] ,

print (data).split('+')

How do I print the sum of these values?

    
asked by anonymous 21.09.2016 / 15:34

2 answers

1

Use sum :

data = ['6', '5'] 

print (sum(int(numero) for numero in data if numero.isdigit())) # 11
    
21.09.2016 / 15:44
0
  

Considering that you will always receive either numeric or   mathematical operations.

First you will separate the data of the string that arrives for you:

>>> string = "6+5".split("+")
>>> string
['6','5']

Then you have to convert them into numbers treatable by python functions, so use int or float . I will use the map function to perform an operation for each element in the list.

>>> operadores = list( map(float,string) )
>>> operadores
[6.0 , 5.0]
>>> soma = sum(operadores)
11.0

Or using fewer variables:

soma = sum ( list ( map ( float,data ) ) )
    
25.09.2016 / 18:11