Converting a String to a Variable Name in Python
Given a string representation, the task is to convert it into a variable name and assign it a certain value. This can be achieved using the exec() function.
Solution:
# Create a string variable x = 'buffalo' # Assign the variable a numeric value using exec() exec("%s = %d" % (x, 2)) # Check the value of the variable print(buffalo)
In this example, the exec() function is employed to dynamically execute a Python expression that creates a variable named buffalo and assigns the value 2 to it. Therefore, the statement exec("%s = %d" % (x, 2)) translates to buffalo = 2.
The %s and %d placeholders are used to format the expression string with the values of x and 2, respectively. The resulting string 'buffalo = 2' is then executed as Python code within the exec() function.
Upon execution, this dynamically created variable buffalo can be accessed and its value can be printed using the print() function, resulting in output:
2
The above is the detailed content of How Can I Dynamically Create and Assign Values to Variables in Python Using a String?. For more information, please follow other related articles on the PHP Chinese website!