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

Asked

Viewed 1,365 times

2

Input value: 6+5

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

print (data).split('+')

how do I print the sum of these values?

2 answers

1

Use the sum:

data = ['6', '5'] 

print (sum(int(numero) for numero in data if numero.isdigit())) # 11

0

Whereas you will always receive either numeric characters or mathematical operations.

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

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

Then you have to turn them into tractable numbers by python functions, for that use the intor the float. I’ll use the function map to perform an operation for each item 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 ) ) )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.