how to use strip in map function

Tomasz Brzezina picture Tomasz Brzezina · Oct 5, 2016 · Viewed 13.4k times · Source

I'd like to use map to get list of strings:

value = '1, 2, 3'

my_list = list(map(strip, value.split(',')))

but got:

NameError: name 'strip' is not defined

expected result: my_list=['1','2','3']

Answer

Martijn Pieters picture Martijn Pieters · Oct 5, 2016

strip is still just a variable, not a reference to the str.strip() method on each of those strings.

You can use the unbound str.strip method here:

my_list = list(map(str.strip, value.split(',')))

which will work for any str instance:

>>> value = '1, 2, 3'
>>> list(map(str.strip, value.split(',')))
['1', '2', '3']

In case you want to call a method named in a string, and you have a variety of types that all happen to support that method (so the unbound method reference wouldn't work), you can use a operator.methodcaller() object:

from operator import methodcaller

map(methodcaller('strip'), some_mixed_list)

However, instead of map(), I'd just use a list comprehension if you want to output a list object anyway:

[v.strip() for v in value.split(',')]