Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympifying strings containing expressions with superscripts

Tags:

python

sympy

I am trying to sympify a string like these

str1="a^0_0"
ns={}
ns['a^0_0']=Symbol('a^0_0')
pprint(sympify(str1,locals=ns))

But I get the following error

Traceback (most recent call last):
  File "cuaterniones_basic.py", line 114, in <module>
    pprint(sympify(str1,locals=ns))
  File "/usr/local/lib/python2.7/dist-packages/sympy/core/sympify.py", line 356, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse u'a^0_0'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1

How can get the symbol I want?

like image 904
davidaap Avatar asked Apr 10 '26 10:04

davidaap


1 Answers

sympify can only parse expressions if they are valid Python (with a few minor exceptions). That means that symbol names can only be parsed if they are valid Python variable names. The solution depends on the exact nature of what you are trying to parse.

  • If the whole string is the symbol name, just use Symbol instead of sympify.

  • If you are constructing the Symbol objects from known strings, wrap them in Symbol('...') in your string, like sympify("Symbol('a^0') + 1").

  • If you know what characters you will see, you can try swapping them before parsing, then swapping them back in the expression with replace.

    >>> sympify('a^0 + 1'.replace('^', '__').replace(lambda a: isinstance(a, Symbol), lambda a: Symbol(a.name.replace('__', '^')))
    a^0 + 1
    

    (don't confuse str.replace and SymPy's expr.replace here).

    This will not work if the characters in your symbol names are also used to represent math outside of the symbol names (like if you use ^ to represent actual exponentiation).

  • In general, you may need to write your own parsing tool. SymPy's parsing utilities in sympy.parsing can help here.

like image 124
asmeurer Avatar answered Apr 12 '26 00:04

asmeurer