0

I have to write a program sums the numbers of a string.

There's a sample code , I wrote

s = '1.23, 2.12, 3.45'
num1 = [:4]
num2 = [5:9]
num3 = [10:]
sum = num1+ num2+ num3
print sum

But that's not efficient . If I take the string from the user then, How could I write that code where I can separate the numbers from that s individually?

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
Tanzir Uddin
  • 51
  • 1
  • 9

3 Answers3

1

You could solve it in 3 steps.

First: Split, with the split function, the string in the ,

s.split(',')

Second: Apply a float conversion, with map function, for every element from the new list

map(float, s.split(','))

Third: Sum all elements from the list, with sum function.

res = sum(map(float, s.split(',')))
print res
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
0

first split it by your sign , then map it to your target

x = s.split(',')
y = map(float,x)
print sum(y)
Koorosh Ghorbani
  • 507
  • 4
  • 14
0

The one liner solution. Split every item by , (comma and space) then convert those to floats and sum them

s = '1.23, 23.5, 56.77'
print(sum([float(x) for x in s.split(", ")]))
#81.5
Keatinge
  • 4,330
  • 6
  • 25
  • 44