0

How can I add two values replacing / between them? I tried with item.replace("/","+") but it only places the + sign replacing / and does nothing else. For example If i try the logic on 2/1.5 and -3/-4.5, I get 2+1.5 and -3+-4.5.

My intention here is to add the two values replacing / between them and divide it into 2 so that the result becomes 1.875 and -3.75 respectively if I try the logic on (2/1.5 and -3/-4.5).

This is my try so far:

for item in ['2/1.5','-3/-4.5']:
    print(item.replace("/","+"))

What I'm having now:

2+1.5
-3+-4.5

Expected output (adding the two values replacing / with + and then divide result by two):

1.75
-3.75
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
SIM
  • 21,537
  • 4
  • 35
  • 94

6 Answers6

3

Since / is only a separator, you don't really need to replace it with +, but use it with split, and then sum up the parts:

for item in ['2/1.5', '-3/-4.5']:
    result = sum(map(float, item.split('/'))) / 2
    print(result)

or in a more generalized form:

from statistics import mean

for item in ['2/1.5', '-3/-4.5']:
    result = mean(map(float, item.split('/')))
    print(result)
Daniel
  • 40,885
  • 4
  • 53
  • 79
1

You can do it using eval like this:

for item in ['2/1.5','-3/-4.5']:
    print((eval(item.replace("/","+")))/2)
Agile_Eagle
  • 1,572
  • 2
  • 12
  • 27
1

My answer is not that different from others, except I don't understand why everyone is using lists. A list is not required here because it won't be altered, a tuple is fine and more efficient:

for item in '2/1.5','-3/-4.5':            # Don't need a list here
    num1, num2 = item.split('/')
    print((float(num1) + float(num2)) / 2)
cdarke
  • 40,173
  • 7
  • 78
  • 79
1

A further elaboration of @daniel's answer:

[sum(map(float, item.split('/'))) / 2 for item in ('2/1.5','-3/-4.5')]

Result:

[1.75, -3.75]
DYZ
  • 51,549
  • 10
  • 60
  • 87
0
from ast import literal_eval

l = ['2/1.5','-3/-4.5']
print([literal_eval(i.replace('/','+'))/2 for i in l])
iacob
  • 14,010
  • 5
  • 54
  • 92
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
0

You can do it like this(by splitting the strings into two floats):

for item in ['2/1.5','-3/-4.5']:
    itemArray = item.split("/")
    itemResult = float(itemArray[0]) + float(itemArray[1])
    print(itemResult/2)
cdarke
  • 40,173
  • 7
  • 78
  • 79
Gehan Fernando
  • 998
  • 10
  • 22