I have a string
data = "var1 = {'id': '12345', 'name': 'John White'}"
Is there any way in python to extract var1 as a python variable. More specifically I am interested in the dictionary variables so that I can get value of vars: id and name.python
Assuming that you know the string is safe to evaluate, then eval will give the value of the variable in the current context. Do not ever use eval (or exec ) on data that could possibly come from outside the program in any form. It is a critical security risk.
You need to split the string and not strip the string. split returns a list and strip() returns a string with the required substring removed from either side of the string. . split will split the string into a list based on the delimiter and .
Python – Variables in String All we need to do is enclose the variables with curly braces {variable} and place this variable inside the string value, wherever required. An example is given below. In the above program, we have a variable named var1 and we inserted this variable in the string using formatted strings.
In the top-level code environment, the value of __name__ is "__main__" . In an imported module, the value of __name__ is the module's name as a string.
This is the functionality provided by exec
>>> my_scope = {}
>>> data = "var1 = {'id': '12345', 'name': 'John White'}"
>>> exec(data, my_scope)
>>> my_scope['var1']
{'id': '12345', 'name': 'John White'}
You can split the string with =
and evaluated the dictionary using ast.literal_eval
function:
>>> import ast
>>> ast.literal_eval(ata.split('=')[1].strip())
{'id': '12345', 'name': 'John White'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With