Pujan
Pujan

Reputation: 3254

Python String to List with RegEx

I would like to convert mystring into list.

Input : "(11,4) , (2, 4), (5,4), (2,3) "
Output: ['11', '4', '2', '4', '5', '4', '2', '3']



>>>mystring="(11,4) , (2, 4), (5,4), (2,3)"
>>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces
>>>print mystring
(11,4),(2,4),(5,4),(2,3)

>>>splitter = re.compile(r'[\D]+')
>>>print splitter.split(mystring)
['', '11', '4', '2', '4', '5', '4', '2', '3', '']

In this list first and last element are empty. (unwanted)

Is there any better way to do this.

Thank you.

Upvotes: 1

Views: 210

Answers (3)

Savino Sguera
Savino Sguera

Reputation: 3572

>>> alist = ast.literal_eval("(11,4) , (2, 4), (5,4), (2,3) ")

>>> alist
((11, 4), (2, 4), (5, 4), (2, 3))

>>> anotherlist = [item for atuple in alist for item in atuple]
>>> anotherlist
[11, 4, 2, 4, 5, 4, 2, 3]

Now, assuming you want list elements to be string, it would be enough to do:

>>> anotherlist = [str(item) for atuple in alist for item in atuple]
>>> anotherlist
['11', '4', '2', '4', '5', '4', '2', '3']

The assumption is that the input string is representing a valid python tuple, which may or may not be the case.

Upvotes: 0

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

>>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ")
['11', '4', '2', '4', '5', '4', '2', '3']

Upvotes: 8

a'r
a'r

Reputation: 36989

It would be better to remove whitespace and round brackets and then simply split on comma.

Upvotes: 1

Related Questions