Take the 2-minute tour ×

I've split a string by [ and ] but I want these characters to still appear. How do I do this?

words = [beginning for ending in x.split('[') for beginning in ending.split(']')]
share|improve this question
Where do you ant them to appear? In the left part? In the right part? In both of them? –  Sven Marnach Nov 21 '11 at 0:29
Tagged "homework" because it's a follow-up to this question, which is tagged "homework". –  Sven Marnach Nov 21 '11 at 0:31
I don't understand quite well what you're trying to do. Show us a test case and the expected result. –  juliomalegria Nov 21 '11 at 0:33
...or in their own position in the list –  wim Nov 21 '11 at 0:33
Have you looked at str.partition? –  Daenyth Nov 21 '11 at 0:33

2 Answers 2

up vote 3 down vote accepted

I think you need re.split to do this easily:

>>> import re
>>> s = 'Hello, my name is [name] and I am [age] years old'
>>> re.split(r'(\[|\])', s)
['Hello, my name is ', '[', 'name', ']', ' and I am ', '[', 'age', ']', ' years old']
share|improve this answer

Would need to know more about the context of your list and what x, beginning, and ending are, but here are some suggestions.

You can add [ and ] to each item in the list, and return a new list, like this:

["[%s]" % s for s in some_list]

Or, string.join will return a string from the items in a list joined by a given string:

share|improve this answer

Your Answer


