-3

Hi everyone i have a pattern (using django)

[[u'13'], [u'12', u'23'], [u'30', u'31']]

and i want to spilt this and want to append into a list like [13,12,23,30,31] I know this can be done using regular expression but unable to make regualr expression for that. Please help into this Thanks in advance.

Cp Verma
  • 462
  • 5
  • 19

2 Answers2

1

You can use the ast library in order to make the string a python list.

After, iterate through the list and chain all items into one list.

import ast

st = "[[u'13'], [u'12', u'23'], [u'30', u'31']]"

li = ast.literal_eval(st) # you can use this library in order to make the string a python list.
new_li = [item for inner_list in li for item in inner_list]

print (new_li)

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

You could do in python3,

In [8]: [int(s) for i in a for s in i]
Out[8]: [13, 12, 23, 30, 31]
zaidfazil
  • 9,017
  • 2
  • 24
  • 47