Python detects if the string contains characters in a character set

Source: Internet
Author: User
Tags character set iterable

This article mainly describes whether the python detection string contains characters in a character set, the need for friends can refer to the following

Objective

Detects whether characters in a character set are included in a string

Method

The most concise method is the following, clear, universal, fast, applicable to any sequence and container

The code is as follows:

def containany (Seq,aset):

For C in SEQ:

If C in Aset:

Return True

Return False

The second application of the Itertools module to improve performance is essentially the same method as the former (although this approach violates Python's core view: simplicity, clarity)

Description of Itertools.ifilter (predicate, iterable)

Make a iterator that filters elements to iterable returning only those to which the predicate is True. IF predicate is None, return the items that are true.

For example:

IFilter (Lambda x:x%2, Range ())--> 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 detect whether two strings are included, you must check all the subkeys, preferably the set type, where set (Aset). Difference (seq) is an element that is present in aset but not in seq:

The code is as follows:

def containall (Seq,aset):

Return not set (Aset). difference (seq)

For example, the following example:

The code is as follows:

In [4]: l1=[1,2,3,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.symmetric_difference refers to elements unique to two collections

The code is as follows:

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

In [ten]: X=set (L1)

In [one]: x.symmetric_difference (L2)

OUT[11]: Set ([1, 5])

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.