Go full functional with map
and filter
by using:
s = ' 1 , 2 , , , 3 '
res = filter(None, map(str.strip, s.split(',')))
though similar to @omu_negru's answer, this avoids using lambda
s which are arguably pretty ugly but, also, slow things down.
The argument None
to filter translates to: filter on truthness, essentially x for x in iterable if x
, while the map
just maps the method str.strip
(which has a default split value of whitespace) to the iterable obtained from s.split(',')
.
On Python 2, where filter
still returns a list, this approach should easily edge out the other approaches in speed.
In Python 3 one would have to use:
res = [*filter(None, map(str.strip, s.split(',')))]
in order to get the list back.