Reputation: 95
I have a string like;
'[abc] [def] [zzz]'
How would I be able to split it into three parts:
abc
def
zzz
Upvotes: 0
Views: 87
Reputation: 39659
Another way:
s = '[abc] [def] [zzz]'
s = [i.strip('[]') for i in s.split()]
Upvotes: 0
Reputation:
You can use re.findall
:
>>> from re import findall
>>> findall('\[([^\]]*)\]', '[abc] [def] [zzz]')
['abc', 'def', 'zzz']
>>>
All of the Regex syntax used above is explained in the link, but here is a quick breakdown:
\[ # [
( # The start of a capture group
[^\]]* # Zero or more characters that are not ]
) # The end of the capture group
\] # ]
For those who want a non-Regex solution, you could always use a list comprehension and str.split
:
>>> [x[1:-1] for x in '[abc] [def] [zzz]'.split()]
['abc', 'def', 'zzz']
>>>
[1:-1]
strips off the square brackets on each end of x
.
Upvotes: 3