sandeep
sandeep

Reputation: 3345

Extract a list from a string using 're'

I have a string in this format: any_string = "[u'02', u'03', u'04', u'05']". I want to extract a list from this which should look like new_list = ['02', '03', '04', '05']

I am using 're'. The below code i am writing to get this work done, but no luck

import re

new_list = re.findall(r'["w "]', any_string)

I am getting the result as [' ', ' ', ' ']

Basically I want a list like this new_list = ['02', '03', '04', '05'], so that i can loop through the individual items like 02, 03, 04 , 05

Upvotes: 1

Views: 126

Answers (2)

Nathan Villaescusa
Nathan Villaescusa

Reputation: 17629

I'd question where you are getting this string from. It looks like a list that has been passed through str() or repr(). If you need to seralize a list into a string either use JSON or pickle.

Upvotes: 3

RocketDonkey
RocketDonkey

Reputation: 37249

If you aren't tied to re, what about ast? Just one more letter :)

In [1]: import ast

In [2]: any_string = "[u'02', u'03', u'04', u'05']"

In [3]: my_list = ast.literal_eval(any_string)

In [4]: type(my_list)
Out[4]: <type 'list'>

In [5]: my_list
Out[5]: [u'02', u'03', u'04', u'05']

In [6]: for item in my_list:
   ...:     print item
   ...:
   ...:
02
03
04
05

Upvotes: 8

Related Questions