[Tutor] String as a Variable?

D-Man dsh8290@rit.edu
Fri, 2 Feb 2001 11:23:03 -0500


On Fri, Feb 02, 2001 at 10:52:14AM -0500, Seelinger, Bruce wrote:
| Another newbie question...
| 
| Is there a way to have a string represent a variable.
| 
| For eaxample, I have a the following:
| 
| <snip>
| 
| serial_number = '3'
| print 'ip_address_serial_' + serial_number
| ip_address_serial_3
| 
| Now I want to use the string ip_address_serial_3 to pull
| the value assigned to the variable of the same name.
| 
| How can I represent the string as a variable?
| 

You can do this using exec, but it is not recommended.  exec is a
fairly slow statement, and it can have ugly side effects.  For
example, suppose you end up with a name that conflicts with a local or
even worse a global variable in your program?

The recommended technique is to use a dictionary instead.  You can
have a dict, say ip_address_serials, and use the serial_number's as
keys.

ip_address_serials = { }
serial_number = find_serial_number( )
ip_address_serials[ serial_number ] = \
	"whatever value you want associated with it"

for serial_number in ip_address_serials.keys() :
	print "ip_address_serial is:", serial_number

| Thanks in advance.
| 

HTH,
-D