19

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']

Tomasz Brzezina
  • 1,452
  • 5
  • 21
  • 44

2 Answers2

44

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(',')]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Perfect answer, first I use map to convert '1, 2, 3' into [1,2,3] list(map(int,value)), but than I changed mind and fixed on map. But list comprehension is more pythonish – Tomasz Brzezina Oct 06 '16 at 08:41
  • @TomaszBrzezina: I think the `map` approach is as pythonic as the list comprehension. `map` is *meant* for this use case. It's also shorter and performs better as a bonus. – MestreLion Jul 28 '20 at 13:33
  • What if we want to strip something other than space? Like `_` How do we pass it ? – Hayat Dec 14 '20 at 02:46
  • @Hayat `methodcaller()` also takes arguments: `methodcaller('strip', '_')` – Martijn Pieters Dec 15 '20 at 08:59
7

You can also use a lambda to achieve your purpose by using:

my_list = map(lambda x:x.strip(), value.split(","))

where each element in value.split(",") is passed to lambda x:x.strip() as parameter x and then the strip() method is invoked on it.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Zixian Cai
  • 945
  • 1
  • 10
  • 17