RRR RRR - 4 months ago 8
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

x=['reg1','reg2','reg3']


I want to write:

for reg in x:
display_value.reg


Such that python reads the following for every iteration:

display_value.regX


and NOT:

display_value.'regX'

Answer

What you want is getattr:

x=['reg1','reg2','reg3']

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.