21
votes

The default split method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are not collapsed:

>>> 'aaa'.split('a')
['', '', '', '']

What is the most straightforward way to collapse consecutive delimiters? I know I could just remove empty strings from the result list:

>>> result = 'aaa'.split('a')
>>> result
['', '', '', '']
>>> result = [item for item in result if item]

But is there a more convenient way?

6
Seems like you could accomplish this with re.split - Chris Eberle
Interesting! I didn't realize split() with no arguments did something that couldn't be replicated by split with arguments. - weronika

6 Answers

13
votes

You can use re.split with a regular expression as the delimiter, as in:

re.split(pattern, string[, maxsplit=0, flags=0])
26
votes

This is about as concise as you can get:

string = 'aaa'
result = [s for s in string.split('a') if s]

Or you could switch to regular expressions:

string = 'aaa'
result = re.split('a+', string)
2
votes

You could use regular expressions:

re.split(pattern, string[, maxsplit=0, flags=0])

as

re.split('a+', 'aaa')
1
votes

I think your solution is perfectly OK. Here's an equivalent one:

filter(bool, 'aaa'.split('a'))

Probably not as perspicuous as a list comprehension, though.

0
votes

No, there isn't a more convenient way. Either you write your own split function, or do the removing empty strings.

But your solution seems very clear and pythonic.

0
votes

Although it's not exactly what you asked for, you can get rid of all non-unique tokens by using a set:

>>> result
['', '', '']
>>> set(result)
set([''])