0

Say you have:

text = "22 + 33"

And you want to verify that the sign used it is actually an addition sign:

for word in text:
    If word == "+":
  1. How do I find the index/position of the addition sign inside the string?
  2. How do you find the index/position of the numbers to the sides of the addition sign?

I want to do this to then assign these values to variables and then be able to calculate the problem.

PD: The problem is that, the string is not only going to have the addition and thats it, it will contain much more words and signs. Plus, it will be constantly updating (every 0.5 secs). Thats why I want to locate if there is an ADDITION sign and then find the two numbers to its sides to consecuently calculate the sum. Therefore, following my approach, I should need the indexes of the the three things; number1, addition sign and number 2.

Liubey135
  • 19
  • 4

1 Answers1

0

You can use the eval() function in Python to evaluate an expression. For example, consider the following code:

text = "22 + 33"
print(eval(text))

This will print out 55, which is 22 + 33

Jack Morgan
  • 317
  • 1
  • 14
  • 2
    wow never heard of that function, thank you very much – Liubey135 Jan 20 '21 at 20:45
  • But that doesn't answer his questioj – chess_lover_6 Jan 20 '21 at 20:53
  • 1
    @chess_lover_6 It does, OP wanted to calculate an addition presented as a string. Although this is not the way that OP intended to solve this problem, it still does what he asks. Note: 'PD: Is there a better way to do this?' – Jack Morgan Jan 20 '21 at 20:56
  • 1
    I mean it works, but he was asking, How do I find the index/position of the addition sign inside the string? How do you find the index/position of the numbers to the sides of the addition sign?. I mean it was helpful and works. – chess_lover_6 Jan 20 '21 at 20:57
  • 1
    @chess_lover_6 I think this comes down to our interpretation of the question as OP was really asking more than one separate question. I was focussing more on the point that he wants to 'be able to calculate the problem'. But yes, I see your point. – Jack Morgan Jan 20 '21 at 21:01