0

I want to do something like this in Python:

a_string = 'variable_name'
print('{0}'.format(variable_name))

That is, I want to extract a variable's name from the string and send it into .format(). How can I do?

2
  • What do you want to be printed here? Commented May 5, 2014 at 13:38
  • 1
    if you have data in your variable names, you shouldn't. Commented May 5, 2014 at 13:47

3 Answers 3

4

This, in general, is not considered a good practice - data should be data, and code should be code. There are, of course, exceptions to that general rule.

To do what you want, you can simply access the dictionary returned by a call to vars:

a_string = 'variable_name'
print('{0}'.format(vars()[variable_name]))

vars checks the variable availability in the local context (the same as a call to locals())

Back to good practices: if you need strings to locate data in your program, you should check if you could not be using a dictionary instead of letting this data, with dynamic name, directly in a variable. One of the main purposes of dictionaries is allowing dynamic look-up of data.

Sign up to request clarification or add additional context in comments.

Comments

3

The usual way is to use the dictionary form of str.format

>>> variable_name = 'hello'
>>> print('{variable_name}'.format(**vars()))
hello

Comments

1

You can do that as:

a_string = 'variable_name'
print('{0}'.format(globals()[a_string]))

Example

variable_name = 'hello'

a_string = 'variable_name'
>>> print('{0}'.format(globals()[a_string]))
hello

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.