Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to pass methods as parameters?

Tags:

python

I'm a bit new to programming, so I'm sorry if this is obvious: is there a better way than shown below to pass methods as parameters?

The following code takes a string and prints out if there are any numbers, upper/lower case characters, etc. in it:


    s = input()

    def func1(string):
        return string.isalnum()

    def func2(string):
        return string.isalpha()

    def func3(string):
        return string.isdigit()

    def func4(string):
        return string.islower()

    def func5(string):
        return string.isupper()

    def stringthing(func, s):
        for i in range(0, len(s)):
            if func(s[i]):
                return True

        return False 

    print(stringthing(func1, s))
    print(stringthing(func2, s))
    print(stringthing(func3, s))
    print(stringthing(func4, s))
    print(stringthing(func5, s))

This works, but could it be more compact (i.e. not making 5 new functions)? I couldn't find anything out there, but maybe I don't know what I'm looking for.

like image 423
Sign Avatar asked Jan 24 '23 07:01

Sign


1 Answers

You can use the class methods of str directly:

print(stringthing(str.isalnum, s))
print(stringthing(str.isalpha, s))
print(stringthing(str.isdigit, s))
print(stringthing(str.islower, s))
print(stringthing(str.isupper, s))
like image 144
enzo Avatar answered Jan 26 '23 21:01

enzo