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!

asked Sep 22, 2015 at 11:48
1

2 Answers 2

2

Use a dictionary.

d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])
answered Sep 22, 2015 at 11:57
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.

answered Sep 22, 2015 at 12:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.