Skip to main content
2 of 4
added 10 characters in body
Curt F.
  • 1.7k
  • 11
  • 22

check a string for any occurrences of certain character classes

You are given a string S. Your task is to find if string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.

Input Format

Single line containing, string S.

Constraints

0<len(S)<1000

Output Format

  • In First line, print True if S has alphanumeric character otherwise print False.
  • In Second line, print True if S has alphabetical character otherwise print False.
  • In Third line, print True if S has digits otherwise print False.
  • In Fourth line, print True if S has lowercase character otherwise print False.
  • In Fifth line, print True if S has uppcase character otherwise print False.

This is a warm-up programming exercise for learning string methods in Python from HackerRank.

My working solution is here:

def parse_input():
    string = raw_input()
    return string

def check_string(string):
    check_funs = [str.isalnum,
                  str.isalpha,
                  str.isdigit,
                  str.islower,
                  str.isupper,
                  ]
    return [any(fun(char) for char in string) for fun in check_funs]

def print_output(results):
    for el in results:
        print el
        
if __name__ == '__main__':
    string = parse_input()
    print_output(check_string(string))

Apologies for the lack of docstrings; I think aside from that, I'm PEP8 compliant but please let me know if I missed something. I'm interested in any and all feedback of course, but in particular:

  • I feel like my check_string() function isn't very pretty. What's the preferred syntax for folding a list of class methods into a list comprehension? I found a possibly relevant Stack Overflow question but couldn't quite make heads or tails of it. It just doesn't seem right to have to do str.method to refer to a function, but then call it with fun(my_string) for fun in func_list instead of my_string.fun() for fun in func_list. (But that latter bit doesn't work of course.)

What are some better ways?

Curt F.
  • 1.7k
  • 11
  • 22