| | |
setting a string as a variable name
Thread Solved |
•
•
Join Date: Feb 2008
Posts: 1
Reputation:
Solved Threads: 0
I just started using python a couple of days ago, so I am a complete beginner. Basically what I am trying to do is the following. Imagine that I have a string variable such as:
food = 'bread'
I want to create another variable (integer or another type) so that its name is 'bread', in other words the new variable name should be the value of the string variable "food". How can I do such an assignment? My guess is that it should not take more than two or three lines. I read up and am thinking that I need to use a function called setattr, but am not able to figure out how to use it.
Thank you in advance.
food = 'bread'
I want to create another variable (integer or another type) so that its name is 'bread', in other words the new variable name should be the value of the string variable "food". How can I do such an assignment? My guess is that it should not take more than two or three lines. I read up and am thinking that I need to use a function called setattr, but am not able to figure out how to use it.
Thank you in advance.
Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:
You can print out vars() to see what's going on.
python Syntax (Toggle Plain Text)
food = 'bread' vars()[food] = 123 print bread # --> 123
No one died when Clinton lied.
![]() |
Similar Threads
- help with IsNumeric function (C++)
- Querying a blank string (C)
- Updating a file: setting the offset (Perl)
- Setting up a cookie and saving the result in mySQL database (PHP)
- pass variable (Java)
- Setting a variable to the Exit Code (Python)
- problem with fstream (C++)
- Geting elements from a String Array (C++)
- need help in creating class string (C++)
Other Threads in the Python Forum
- Previous Thread: setting PATH through python
- Next Thread: Using wxPython for Windows GUI programming
| Thread Tools | Search this Thread |
abrupt alarm ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd code customdialog cx-freeze data decimals dictionaries dictionary directory dynamic error examples exe file float format function gnu graphics gui halp heads homework http ideas import input java launcher leftmouse line linux list lists loop module mouse number numbers output parsing path pointer port prime programming progressbar projects push py2exe pygame pyglet pyqt python random recursion schedule screensaverloopinactive script scrolledtext sqlite statistics string strings sudokusolver sum table terminal text thread threading time tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable ventrilo wikipedia write wxpython xlib






