A small example shows you the elegance of the Python language

  • 2020-04-02 13:48:20
  • OfStack

For example, we want to detect "does a string end with a particular string ?" , usually we use:


  if needle.endswith('ly') or needle.endswith('ed') or
    needle.endswith('ing') or needle.endswith('ers'):
    print('Is valid')
  else:
    print('Invalid')

Very ugly isn't it ? If we test whether the variable needle is one of the following specific strings, we will write:


  if needle in ('ly', 'ed', 'ing', 'ers'):
    print('Is valid')
  else:
    print('Invalid')

However, we can't use in in the endswith function, but instead we need to check that "a string ends in any of the following string ?" , we will find that python has an internal function any, so our code can be changed to:


  if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]):
    print('Is valid')
  else:
    print('Invalid')

I'm sure many readers will disagree with me here, or that there is a better way to write it, but it doesn't matter anymore.


Related articles: