Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse consecutive delimiters?

Tags:

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?

like image 820
Channel72 Avatar asked Jun 25 '11 15:06

Channel72


People also ask

Can you split on multiple delimiters Python?

To split a string with multiple delimiters in Python, use the re. split() method. The re. split() function splits the string by each occurrence of the pattern.

What is default delimiter of the split () function?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.


2 Answers

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) 
like image 76
orlp Avatar answered Sep 17 '22 18:09

orlp


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

re.split(pattern, string[, maxsplit=0, flags=0]) 
like image 44
Assaf Lavie Avatar answered Sep 18 '22 18:09

Assaf Lavie