Reputation: 383
Let's assume I have a string
st = "'aaa': '1', 'bbb': '2.3', 'ccc': 'name'"
I want to extract from st the following
['1', '2.3', 'name']
How can I do this?
Thanks
Upvotes: 3
Views: 52
Reputation: 17074
Doing it with ast
module would be best, like jezrael did it. Here is another solution with regex:
import re
st = "'a': '1', 'b': '2.3', 'c': 'name', 'd': 229, 'e': '', 'f': '228', 'g': 12"
print re.findall(r'\'\S+?\':\s*\'?(.*?)\'?(?:,|$)', st)
Output:
['1', '2.3', 'name', '229', '', '228', '12']
Demo on regex101:
https://regex101.com/r/zGAt4D/5
Upvotes: 4
Reputation: 863731
You can first create dict
by ast.literal_eval
and then get values
:
import ast
st = "'aaa': '1', 'bbb': '2.3', 'ccc': 'name'"
print (ast.literal_eval('{' + st + '}'))
{'aaa': '1', 'bbb': '2.3', 'ccc': 'name'}
#python 3 add list
print (list(ast.literal_eval('{' + st + '}').values()))
['1', '2.3', 'name']
#python 2
print ast.literal_eval('{' + st + '}').values()
['1', '2.3', 'name']
Upvotes: 5