RRR RRR - 1 year ago 54
Python Question

Changing a string to variable

I'm working with Python 2.6 here.
Perhaps my title is misleading. So I will explain here. I tried my best to search for a solution, but since I'm rather new I have no clue what to search.

Essentially, I'm getting an input string value from the user, and I wish to do the following:

Let's say


I want to write:

for reg in x:

Such that python reads the following for every iteration:


and NOT:


Answer Source

What you want is getattr:


for attr in x:                   
    getattr(display_value, attr) # same as display_value.attr, attr not a string.

You may find it useful to provide a default value in case your object doesn't have the attr:

foo = getattr(obj, attr, 'default value') # typically better to use None.