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']
>>开发者_JAVA百科;>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.
>>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ")
['11', '4', '2', '4', '5', '4', '2', '3']
It would be better to remove whitespace and round brackets and then simply split on comma.
>>> 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.
精彩评论