![]() ![]() If there are no syntax errors found, the string is executed as python code. The object code is executed as is while the string is first parsed and checked for any syntax error. The code can be passed in as string or object code to this function. Output is, 20.0 Approach #3 – Using exec() functionĮxec function can dynamically execute code of python programs. Print(dict) # Access the value like this, with the help of key Example dict = #Initialize a dictionaryĭict = 20.0 # Make the string a key in dictionary and assign the value of your choice It is much less prone to errors and security risks. The most recommended way to do this is to use a dictionary. Output is, 20.0 Approach 3 – Using a dictionary The scope of vars() will be exactly the same as the scope of x. ![]() When used without any argument, it behaves just like locals(). Vars() provides low-level access to variables created by python. def create_pika(x,value = 10):Ĭreate_pika("pikachu",20) # Creates a variable pikachu and assign value 20 to it. Since inside the function it is going to be a locally scoped variable, we will use locals(). In the below example, we will create a variable inside a function. If we need to create the variable in a local scope, we will use locals() instead of globals(), the rest should be the same. We can use globals() and locals() to convert string value to a variable. pikachu = 10 Approach #1 – Using globals() and locals() To a variable pikachu to store integer value(or any other datatype you want). Sharing some of the approaches below which can be used to dynamically convert string values to variable names. There may be times when you need to do that too. I explored a bit and was able to get it done. I had a list of strings that I had to convert to variable names to store the integer values. I was doing a task lately and there, got a need to convert some strings to variable names. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
June 2023
Categories |