f string used to make symbols

44 views
Skip to first unread message

Zohreh Karimzadeh

unread,
Aug 13, 2022, 8:06:01 AM8/13/22
to sympy
Dear sympy
Thank millions  for sharing and caring!
I need to create and use symbols in dynamic way. Infact symbols are made based on user input and used in code so I must use f'strings to make them.
As shown below:
L=[ 'xCl', 'xNa']
for j in range(len(L)):
     locals()[L[j]] = sympy.symbols(L[j])
ss = xCl * xNaCl
i = 'Na'
j='Cl'
gg =f"x{i}"* f"x{j}"
print('gg', gg)
But I got the following error
TypeError: can't multiply sequence by non-int of type 'Symbol'
Could possibly let me know how can do it??

Chris Smith

unread,
Aug 13, 2022, 9:36:50 AM8/13/22
to sympy
`var` will inject the symbols into the namespace. But you could also use parse_expr and pass it a dictionary with the symbols to use:

from sympy import parse_expr, symbols, var
v =  ['xa', 'xb']
xa, xb = map(var, v)
ok = xa*xb
better = parse_expr('xa*xb', local_dict=dict(zip(v, symbols(v))))

Chris
/c

Aaron Meurer

unread,
Aug 13, 2022, 7:36:47 PM8/13/22
to sy...@googlegroups.com
You are trying to multiply the strings but you really want to multiply symbols. Something like Symbol(f"x{i}")*Symbol(f"x{i}").

There should be no need to inject symbols into locals to do what you are trying to do. Symbols do not have to be assigned to a variable to work. 

Aaron Meurer 

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/6e80be54-2134-460f-9125-08f0d99def73n%40googlegroups.com.

Jeremy Monat

unread,
Aug 13, 2022, 9:25:53 PM8/13/22
to sy...@googlegroups.com
While outside the scope of your question, it seems like you're doing chemistry and that's my background so I can't help but mention that ChemPy, which is based on SymPy, can parse chemical formulas into substances and then return properties such as mass (molecular weight):

>>> from chempy import Substance
>>> for chemical in ['Na','Cl','NaCl']:
     substance = Substance.from_formula(chemical)
    mass = substance.mass
     print(mass)
22.98976928
35.45
58.43976928000001

Jeremy Monat

P.S. I actually used that ChemPy functionality, along with SymPy, to develop a cheminformatics app.

Zohreh Karimzadeh

unread,
Aug 13, 2022, 10:46:54 PM8/13/22
to sy...@googlegroups.com
Thank you all;)
Zohreh Karimzadeh
Skype Name 49a52224a8b6b38b
Twitter Account @zohrehkarimzad1
+989102116325                                                        
((((((((((((((((Value Water)))))))))))))))


Reply all
Reply to author
Forward
0 new messages