Split by regex without resulting empty strings in Python -
this question has answer here:
i want split string containing irregularly repeating delimiter, method split() does:
>>> ' b c de '.split() ['a', 'b', 'c', 'de'] however, when apply split regular expression, result different (empty strings sneak resulting list):
>>> re.split('\s+', ' b c de ') ['', 'a', 'b', 'c', 'de', ''] >>> re.split('\.+', '.a.b...c..de..') ['', 'a', 'b', 'c', 'de', ''] and want see:
>>>some_smart_split_method('.a.b...c..de..') ['a', 'b', 'c', 'de']
the empty strings inevitable result of regex split (though there reasoning why behavior might desireable). rid of them can call filter on result.
results = re.split(...) results = list(filter(none, results)) note list() transform necessary in python 3 -- in python 2 filter() returns list, while in 3 returns filter object.
Comments
Post a Comment