ab1127
ab1127

Reputation: 95

String split on specific characters

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

Answers (2)

Aamir Rind
Aamir Rind

Reputation: 39659

Another way:

s = '[abc] [def] [zzz]'
s = [i.strip('[]') for i in s.split()]

Upvotes: 0

user2555451
user2555451

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

Related Questions