I'm trying to pass a method, specifically a method of the string class, to a function which will run it. My code looks something like:
def foo (list):
for in_str in list[0]:
print(in_str.list[1]())
# format of list
list = [
[["Hello world!", "helloworld"], str.isalpha]
]
The desired operation of the function would be to invoke the isalpha method on the string in_str then print the result. This doesn't work because in_str obviously doesn't have the attribute list, but I want to know how to make list[1] reference the method.
Any suggestions?
Thanks!
2 Answers 2
def foo (l):
for in_str in l[0]:
print(l[1](in_str))
# format of list
l = [["Hello world!", "helloworld"], str.isalpha]
print(foo(l))
You need to pass a string to str.isalpha, also you have an extra pair of brackets in the list.
In [2]: foo(l)
False
True
If you just want to pass a function then pass it as a parameter and just pass a list of strings:
def foo(l, func):
for in_str in l[0]:
print(func(in_str))
l = ["Hello world!", "helloworld"]
print(foo(l,str.isalpha))
A nicer way may be to use map to map the func to each string:
def foo(l,func):
return map(func,l) # list(map(...) python 3
print(foo(l,str.isalpha))
7 Comments
print(foo(l[0]))l[0], in_str `would be a list. If not we can do a little changeEither you call the function isalpha with a string as an argument:
str.isalpha('Hello World!")
or as an object oriented approach:
'Hello World'.isalpha()
In your case we also need to correct some indices. I also changed the variable name list because it shadows the built-in list function.
def foo(anestedlist):
for a_str in anestedlist[0][0]:
print(anestedlist[0][1](a_str))
# format of list
anestedlist = [[["Hello world!", "helloworld"], str.isalpha]]
and
foo(anestedlist)
prints
False
True
The important part here is
print(anestedlist[0][1](a_str))
which translates to str.isalpha(a_str), i.e. passing a string as an argument.