3

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

2 Answers 2

5

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But is there another way to do this with regular expression?
check another solution.
4

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

4 Comments

What is there is a number rather than string after ':' ?
@Mansumen Ok I'll improve it
@Mansumen Check now.
@Mansumen Made it more robust to include empty strings as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.