Reputation: 13
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!
Upvotes: 0
Views: 48
Reputation: 122159
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 repr
esentation of the parameter, rather than its s
tring or d
ecimal 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.
Upvotes: 1
Reputation: 76264
Use a dictionary.
d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])
Upvotes: 2