In [1]:
import ast
In [2]:
s = '["a", "b", "c"]'
In [3]:
l = ast.literal_eval(s)
print(l)
In [4]:
print(type(l))
In [5]:
s = '["x", 1, True]'
In [6]:
l = ast.literal_eval(s)
print(l)
In [7]:
print(type(l[0]))
In [8]:
print(type(l[1]))
In [9]:
print(type(l[2]))
In [10]:
s = '{"key1": 1, "key2": 2}'
In [11]:
d = ast.literal_eval(s)
print(d)
In [12]:
print(type(d))
In [13]:
s = '{1, 2, 3}'
In [14]:
se = ast.literal_eval(s)
print(se)
In [15]:
print(type(se))
In [16]:
s = '["x", 1 + 10]'
In [17]:
print(eval(s))
In [18]:
# print(ast.literal_eval(s))
# ValueError: malformed node or string
In [19]:
a = 100
print(eval('[1, a]'))
In [20]:
# a = 100
# print(ast.literal_eval('[1, a]'))
# ValueError: malformed node or string
In [21]:
import json
In [22]:
s = '{"key1": [1, 2, 3], "key2": "abc"}'
In [23]:
print(json.loads(s))
In [24]:
print(ast.literal_eval(s))
In [25]:
s = '[True, False, None]'
In [26]:
# print(json.loads(s))
# JSONDecodeError: Expecting value:
In [27]:
print(ast.literal_eval(s))
In [28]:
s = '[true, false, null]'
In [29]:
print(json.loads(s))
In [30]:
# print(ast.literal_eval(s))
# ValueError: malformed node or string
In [31]:
s = "{'key1': 'abc', 'key2': '''xyz'''}"
In [32]:
# print(json.loads(s))
# JSONDecodeError: Expecting property name enclosed in double quotes
In [33]:
print(ast.literal_eval(s))
In [34]:
s = 'a, b, c'
In [35]:
l = s.split(', ')
print(l)
In [36]:
print(type(l))
In [37]:
s = '1-2-3'
In [38]:
l = s.split('-')
print(l)
In [39]:
print(type(l[0]))
In [40]:
l = [int(c) for c in s.split('-')]
print(l)
In [41]:
print(type(l[0]))