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.
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))
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