简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM