Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Python Help?
I need to define a variable by the contents of a string.
Here's what I need:
NeededVariable = [dir.something['test']]
I have to assemble the contents on the right side for batch processing. So basically I have:
String = "[dir.something['test']]"
But when I try to set NeededVariable=String it obviously turns NeededVariable into a string
NeededVariable = String
Returns:
NeededVariable = "[dir.something['test']]"
So basically I need that but without the quotations on the outside.
Here's an idea I had:
print returns the value without the quotations. Is there a way to set a variable equal to the returned value of print?
Needed variable = print string
1 Answer
- husoskiLv 73 years ago
Use the eval() built-in function to evaluate the contents of a string as a Python expression.
Be careful with this in "production" use, and avoid plain use of eval() on strings that come from user input. Unless you override the local and global name dictionaries, the default is to make all global and local names (modules, functions, variables) visible during the evaluation. That's a danger to program integrity.
See https://docs.python.org/3/library/functions.html#e...
Just below that is the exec() function, which can be used to compile and execute one or more whole statement from a string. This is even more dangerous, as an import statement can load and run arbitrary amounts of code from an external file.
Edit: By the way, your "dir.something['test']" expression doesn't look like anything valid, since dir() is a built-in function. It's possible to reuse that name for a variable or argument, but that hides the built-in definition and is apt to confuse someone trying to read your code.