1

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.

2
  • Do you explicitly need to use regex? Commented Sep 30, 2011 at 14:00
  • 1
    Joke method, don't use this: strings, string = [], '' then for char in "(11,4) , (2, 4), (5,4), (2,3) ": string = string + char if char.isdigit() else strings.append(string) or '' if string else '' and the result is in strings at the end. Commented Sep 30, 2011 at 14:05

3 Answers 3

8
>>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ")
['11', '4', '2', '4', '5', '4', '2', '3']
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

mystring.strip(' \t\r\n()').split(',') and they're called parenthesis not round brackets ;)
0
>>> 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.

1 Comment

As phrased he wants strings, not integers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.