Python checks whether a string contains characters in a character set.

Source: Internet
Author: User

Python checks whether a string contains characters in a character set.

This article mainly introduces whether the Python check string contains characters in a character set. For more information, see

Purpose

Checks whether a string contains characters in a character set.

Method

The simplest method is as follows:

The Code is as follows:

Def containAny (seq, aset ):

For c in seq:

If c in aset:

Return True

Return False

The second method is applicable to the itertools module to improve the performance, which is essentially the same method as the former (but this method violates the core idea of Python: concise and clear)

Itertools. ifilter (predicate, iterable) Description

Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true.

For example:

Ifilter (lambda x: x % 2, range (10) --> 1 3 5 7 9

The Code is as follows:

Import itertools

Def containAny (seq, aset ):

For item in itertools. ifilter (aset. _ contain __, seq ):

Return True

Return False

If you want to check whether two strings are contained, you must check all the sub-items. It is best to apply the set type, where set (aset ). difference (seq) is an element that exists in aset and does not exist in seq:

The Code is as follows:

Def containAll (seq, aset ):

Return not set (aset). difference (seq)

For example:

The Code is as follows:

In [4]: L1 = [1, 2, 4]

In [5]: L2 = [1, 4, 3, 1]

In [6]: containAll (L1, L2)

Out [6]: True

In [7]: containAll (L2, L1)

Out [7]: False

Note that set. effecric_difference refers to the unique elements of two sets.

The Code is as follows:

In [9]: L2 = [3, 2, 4, 5]

In [10]: x = set (L1)

In [11]: x. symmetric_difference (L2)

Out [11]: set ([1, 5])

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.