For example, we want to check whether a string ends with a specific string? ", We usually use:
If needle. endswith ('ly ') or needle. endswith ('ed') or needle. endswith ('in') or needle. endswith ('ers'): print ('is valid') else: print ('invalid ')
Ugly, right? If we check whether the variable needle is one of the following specific strings:
If needle in ('ly ', 'ed', 'ing', 'ers'): print (' Is valid') else: print ('invalid ')
However, we cannot use in endswith function, but we need to check whether the end of a string is any of the following strings? ", We will find that python has an internal function any, so our code can be changed:
If any ([needle. endswith (e) for e in ('ly ', 'ed', 'in', 'ers')]): print (' Is valid') else: print ('invalid ')
I believe many readers will disagree with my practice here, or there is a better way of writing. but this is no longer important. I understand that most of you will use similar writing to address this similar problem. my real purpose is to show the elegance of Python.