J.Zagdoun
J.Zagdoun

Reputation: 124

What are the types of Python operators?

I tried type(+) hoping to know more about how is this operator represented in python but i got SyntaxError: invalid syntax.
My main problem is to cast as string representing an operation :"3+4" into the real operation to be computed in Python (so to have an int as a return: 7).
I am also trying to avoid easy solutions requiring the os library if possible.

Upvotes: 0

Views: 72

Answers (2)

EvertW
EvertW

Reputation: 1180

The built-in eval function probably does what you want:

eval('3+4')

returns 7.

Upvotes: 1

chepner
chepner

Reputation: 531858

Operators don't really have types, as they aren't values. They are just syntax whose implementation is often defined by a magic method (e.g., + is defined by the appropriate type's __add__ method).

You have to parse your string:

  1. First, break it down into tokens: ['3', '+', '4']
  2. Then, parse the token string into an abstract syntax tree (i.e., something at stores the idea of + having 3 and 4 as its operands).
  3. Finally, evaluate the AST by applying functions stored at a node to the values stored in its children.

Upvotes: 7

Related Questions