Thank you, Wayne! This helps a lot. On Nov 4, 2011, at 5:38 PM, Wayne Werner wrote:
> On Fri, Nov 4, 2011 at 4:21 PM, Max S. <[email protected]> wrote: > Is it possible to create a variable with a string held by another variable in > Python? For example, > > >>> var_name = input("Variable name: ") > (input: 'var') > >>> var_name = 4 > >>> print(var) > (output: 4) > > (Yeah, I know that if this gets typed into Python, it won't work. It just > pseudocode.) > > There are a few ways to do what you want. The most dangerous (you should > never use this unless you are 100% absolutely, totally for certain that the > input will be safe. Which means you should probably not use it) method is by > using exec(), which does what it sounds like: it executes whatever is passed > to it in a string: > > >>> statement = input("Variable name: ") > Variable name: var > >>> exec(statement + "=4") > >>> var > 4 > > The (hopefully) obvious danger here is that someone could type anything into > this statement: > > >>> statement = input("Variable name: ") > Variable name: import sys; sys.exit(1); x > >>> exec(statement + " =4") > > and now you're at your prompt. If the user wanted to do something more > malicious there are commands like shutil.rmtree that could do *much* more > damage. > > A much safer way is to use a dictionary: > > >>> safety = {} > >>> safety[input("Variable Name: ")] = 4 > Variable Name: my_var > >>> safety["my_var"] > 4 > > It requires a little more typing, but it also has the advantage of accepting > perfectly arbitrary strings. > > There may be some other ways to do what you want, but hopefully that should > get you started. > HTH, > Wayne
_______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
