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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
SIM
  • 21,997
  • 5
  • 37
  • 109

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
  • 42,087
  • 4
  • 55
  • 81
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,710
  • 3
  • 13
  • 32
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
  • 42,728
  • 8
  • 80
  • 84
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
  • 55,249
  • 10
  • 64
  • 93
0
from ast import literal_eval

l = ['2/1.5','-3/-4.5']
print([literal_eval(i.replace('/','+'))/2 for i in l])
iacob
  • 20,084
  • 6
  • 92
  • 119
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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
  • 42,728
  • 8
  • 80
  • 84
Gehan Fernando
  • 1,221
  • 13
  • 24