Reputation: 213
I have referred to many sources but most use json.loads()
or ast.literal_eval()
which doesn't work for my case:
x = '[(0.0, 58.099669), 56565, Raining]'
Intended output:
x = [(0.0, 58.099669), 56565, 'Raining']
Is there any workaround for this?
Upvotes: 5
Views: 104
Reputation: 1710
What about this:
class default_key(dict):
def __missing__(self, key):
return key
d = default_key()
x = '[(0.0, 58.099669), 56565, Raining]'
res = eval(x, d, {})
# res = [(0.0, 58.099669), 56565, 'Raining']
Explanation: eval
normally uses the globals()
and locals()
dict. However if you don't provide locals()
and replace globals()
with a dict that returns the name of a key when a lookup is done (and the key isn't found), then every 'variable' name in the given list will be converted to a string when eval
is called.
This could still be unsafe however. See this.
Upvotes: 5