Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the math operators strings from module `operator` in python

Take operator.add for example:

>>>import operator as op
>>>op.add(1,2)       #means 1 + 2
3
>>>op.add.__name__
'add'

I want sort of:

>>>op.add.math_str
"+"

Can I get all those math string "+", "-", ">"... module operator supported runtime?

EDIT:

>>> [eval(x) for x in [".".join(("op",x,"__doc__")) for x in dir(op)]]
['abs(a) -- Same as abs(a).',
 'add(a, b) -- Same as a + b.',
 'and_(a, b) -- Same as a & b.',
 'concat(a, b) -- Same as a + b, for a and b sequences.',
 'contains(a, b) -- Same as b in a (note reversed operands).',
 'delitem(a, b) -- Same as del a[b].',
 'delslice(a, b, c) -- Same as del a[b:c].',
 'div(a, b) -- Same as a / b when __future__.division is not in effect.',
 'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.',

above code can list most operators strings, is that means I can list strings with re module?

Thanks!

like image 927
user478514 Avatar asked Jul 09 '26 21:07

user478514


2 Answers

You can use the following table from tutorial to build your own mappings dictionary only once and then simply use it whenever you will need it.

like image 191
Artsiom Rudzenka Avatar answered Jul 11 '26 12:07

Artsiom Rudzenka


No. Build your own dictionary.

like image 41
Ignacio Vazquez-Abrams Avatar answered Jul 11 '26 11:07

Ignacio Vazquez-Abrams