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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With