I am new to python and I am trying to make a program. I need to convert a string to a variable which accepts other strings.
exec('%s = %d' % ("newVar", 87))
This works for integers but is there any format strings like this for strings? Or is there a different method?
Thanks in advance!
-
possible duplicate of How do I do variable variables in Python?jonrsharpe– jonrsharpe2015年09月22日 12:08:18 +00:00Commented Sep 22, 2015 at 12:08
2 Answers 2
Use a dictionary.
d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])
Comments
I think what you're actually looking for is the %r specifier, which will work for both integers and strings:
>>> exec('%s = %r' % ('var1', 2))
>>> exec('%s = %r' % ('var2', 'foo'))
>>> var1
2
>>> var2
'foo'
This uses the representation of the parameter, rather than its string or decimal version:
>>> '%s = %r' % ('var1', 2)
'var1 = 2'
>>> '%s = %r' % ('var2', 'foo')
"var2 = 'foo'"
You can read more about the various specifiers in the documentation.
However, doing "variable variables" like this is rarely the appropriate thing to do - as pointed out in Kevin's answer, a dictionary is a much better approach.