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

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -