Posts

Showing posts from February, 2021

A reason why I love Pythonic way - Series (Part1)

Problem Statement - 1 Lets say we have to validate whether a string has at least one Alphanumeric or Alphabetical or Digit or Lower Case or Upper Case character in it.   Pythonic Solution Like many other programming language , python has also string methods such as  isalnum,  isalpha.  isdigit,  islower, isupper. So to solve the problem with these methods , we need to check each characters of the string against each method. That needs many lines of codes. However, using getattr , any method & list comprehension , we can solve the problem in just three lines of code: s = input () my_methods = [ 'isalnum' , 'isalpha' , 'isdigit' , 'islower' , 'isupper' ] for i in my_methods: print ( any ([ getattr (char , i)() for char in s])) Is not that beautiful code ?  do let me know in comments if you find it hard to understand.  Another pythonic approach is  to solve above problem could be by using  for-else  statements instead of any something like