Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use strip in map function [duplicate]

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

like image 850
Tomasz Brzezina Avatar asked Oct 05 '16 13:10

Tomasz Brzezina


People also ask

How do you use the strip function on a map?

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.

How do I strip a string from a list?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.

What does strip do in Python?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.

How do you strip a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


2 Answers

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(',')]
like image 100
Martijn Pieters Avatar answered Oct 08 '22 23:10

Martijn Pieters


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.

like image 20
Ivan Avatar answered Oct 08 '22 23:10

Ivan