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?
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.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
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)
You can use re.split
with a regular expression as the delimiter, as in:
re.split(pattern, string[, maxsplit=0, flags=0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With