Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use string functions inside map()?

The following example shows the error I am getting when trying to use a string function inside a function call to map. I need help with why this happening. Thanks.

>>> s=["this is a string","python python python","split split split"]
>>> map(split,s)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    map(split,s)
NameError: name 'split' is not defined

though split() is an in-built function, but it still throws this error?

like image 885
Ashwini Chaudhary Avatar asked Jun 07 '12 04:06

Ashwini Chaudhary


2 Answers

It will work fine if you use str.split()

I.e,

s = ["this is a string","python python python","split split split"]
map(str.split, s)

gives:

[['this', 'is', 'a', 'string'],
 ['python', 'python', 'python'],
 ['split', 'split', 'split']]

The error message states: NameError: name 'split' is not defined, so the interpreter doesn't recognize split because split is not a built-in function. In order for this to work you have to associate split with the built-in str object.

Update: Wording improved based on @Ivc's helpful comments/suggestions.

like image 122
Levon Avatar answered Nov 07 '22 10:11

Levon


split is not a built-in function, though str.split is a method of a built-in object. Generally, you would call split as a method of a str object, so that's why it's bound directly.

Check the output from the interpreter:

>>> str
<type 'str'>
>>> str.split
<method 'split' of 'str' objects>
like image 2
Jeff Tratner Avatar answered Nov 07 '22 09:11

Jeff Tratner