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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With