A small example tells you the elegance of the Python language _python

Source: Internet
Author: User

For example, we want to detect whether a string ends with a particular string, and we usually use:

  If Needle.endswith (' ly ') or Needle.endswith (' Ed ') or
    needle.endswith (' ing ') or needle.endswith (' ers '):
    print (' is valid ')
  else:
    print (' Invalid ')

Pretty ugly, huh? If we detect whether the variable needle is one of the following specific strings, this will be the case:

  If needle in (' ly ', ' ed ', ' ing ', ' ers '):
    print (' is valid ')
  else:
    print (' Invalid ')

However, we cannot use in in the EndsWith function, but in another way we need to examine whether the end of a string is any of the following strings, and we will find that Python has an internal function of any, so our code can be changed to:

  If any ([Needle.endswith (e) to E in (' ly ', ' ed ', ' ing ', ' ers ')]:
    print (' is valid ')
  else:
    print (' Invalid ')

I believe that many readers will disagree with me or have a better way of writing. But it's not important anymore. I understand that most of you will use similar wording to face this similar problem. My real goal is actually to show the elegance of Python.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.