Sweptile
Sweptile

Reputation: 13

Strings to Variables containing Strings - Python

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

Answers (2)

jonrsharpe
jonrsharpe

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 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.

Upvotes: 1

Kevin
Kevin

Reputation: 76264

Use a dictionary.

d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])

Upvotes: 2

Related Questions