Anshul
Anshul

Reputation: 7964

regular expression to get data out of a string

I have a string "["Newyork","Delhi","paris"]" . I need to create a list of cities like this:

cities = ["Newyork","Delhi","paris"] 

What would be the regular expression in python for it.I tried for few hours but could not get how to do it.could anyone help me in this?

Upvotes: 0

Views: 120

Answers (4)

wim
wim

Reputation: 362557

How about a literal eval?

>>>import ast
>>>ast.literal_eval('["Newyork","Delhi","paris"]')
['Newyork', 'Delhi', 'paris']

The only catch is you'll need to replace those start and end quotes.

Upvotes: 1

Reinstate Monica
Reinstate Monica

Reputation: 4723

And the obvious ast.literal_eval alternative is

>>> import ast
>>> ast.literal_eval('["Newyork","Delhi","paris"]')
['Newyork', 'Delhi', 'paris']

Upvotes: 1

yurib
yurib

Reputation: 8147

you can use eval() which is a built in python function and doesn't require any modules:

>>> eval('["Newyork","Delhi","paris"]')
['Newyork', 'Delhi', 'paris']

Upvotes: -1

Rik Poggi
Rik Poggi

Reputation: 29302

This is not something that should be done with regular expression.

Maybe you are looking for the json module:

>>> import json
>>> json.loads('["Newyork","Delhi","paris"]')
['Newyork', 'Delhi', 'paris']

Upvotes: 4

Related Questions