Categories
Python Answers

How to get the value of a variable given its name in a string with Python?

Spread the love

Sometimes, we want to get the value of a variable given its name in a string with Python.

In this article, we’ll look at how to get the value of a variable given its name in a string with Python.

How to get the value of a variable given its name in a string with Python?

To get the value of a variable given its name in a string with Python, we can use the globals or getattr functions.

For instance, we write

a = 5

b = globals()['a']

to call globals to return a dict with the global variable names as keys and their values as values.

Therefore, we can get the value of a with globals()['a'].

To get the value of a global variable in a different module, we use getattr.

For instance, we write

import other

print getattr(other, "a")

to get the value of the a global variable in the other module.

Conclusion

To get the value of a variable given its name in a string with Python, we can use the globals or getattr functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *