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