0

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!

1

2 Answers 2

2

Use a dictionary.

d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.