"Python CookBook2" chapter I text-filter characters in a string that are not part of a specified collection && check whether a string is text or binary

Source: Internet
Author: User

filter characters in a string that are not part of a specified collection

Task:

Given a collection of strings that need to be preserved, construct a filter function and apply it to any string s, the function returns a copy of S that contains only the elements in the specified character set.

Solution:  

ImportStringallchars= String.maketrans ("',"')#All chars TabledefMakefilter (Keep): Delchars=allchars.translate (allchars,keep)defThefilter (s):returns.translate (allchars,delchars) #delchars是要删除的字符串list内容returnThefilterif __name__=="__main__": Just_vowels= Makefilter ('Aeiouy')    PrintJust_vowels ('I love Python')    PrintJust_vowels ('wwwwwwwwww')

checks whether a string is text or binary

Task:

In Python, a normal string can contain either text or any byte, and it is now necessary to find out whether the data in a string is text or binary.

Solution:

  

 from __future__ ImportDivisionImportstringtext_characters="'. Join (Map (Chr,range (32,127)) +'\n\t\r\b'_null_trans= String.maketrans ("',"')defIstext (s,textcharacters = Text_characters,threshold = 0.30):    if ' /' inchS:returnFalseif  notS:returnTrue T=s.translate (_null_trans,text_characters)returnLen (t)/len (s) <=ThresholdPrintIstext ('1101111111')

Still do not understand this method, the structure of the code is still in the learning adaptation

"Python CookBook2" chapter I text-filter characters in a string that are not part of a specified collection && check whether a string is text or binary

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.