Python3 built-in function table.md

[ TOC]

0 x00 Python built-in commonly used functions####

**Q: How to view built-in functions and methods? **
A: dir (builtins) or dir (module), to help query the description of specific methods

>>> import builtins
>>> dir(builtins)['ArithmeticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError','BytesWarning','ChildProcessError','ConnectionAbortedError','ConnectionError','ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError','Ellipsis','EnvironmentError','Exception','False','FileExistsError','FileNotFoundError','FloatingPointError','FutureWarning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','InterruptedError','IsADirectoryError','KeyError','KeyboardInterrupt','LookupError','MemoryError','NameError','None','NotADirectoryError','NotImplemented','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','PermissionError','ProcessLookupError','RecursionError','ReferenceError','ResourceWarning','RuntimeError','RuntimeWarning','StopAsyncIteration','StopIteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TimeoutError','True','TypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeWarning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError']['__build_class__','__debug__','__doc__','__import__','__loader__','__name__','__package__','__spec__',]

# Built-in function
[' abs','all','any','ascii','bin','bool','bytearray','bytes','callable','chr','classmethod','compile','complex','copyright','credits','delattr','dict','dir','divmod','enumerate','eval','exec','exit','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','license','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']

(1) input (prompt string) //The function can be used to input the value and return to the variable is a character type.

(2) type(variable) //The function can be used to query the type of object pointed to by the variable.

(3) isinstance(variable, type) //The function can be used to query whether the variable is of this type and determine whether the object a is an instance object of class A.

(4) The assert expression // asserts that when the condition following this keyword is false, the program automatically crashes and throws an AssertionError exception, which is often used in program placement checkpoints.

(5) range(start,stop,step) //Generate a sequence of numbers from the start parameter value to the stop parameter value.

(6) id(variable) //The function is used to obtain the memory address of the object.

(7) sorted(iterator) //Return the sorted list function similar to list.sort()

(8) reversed() //is an object and returns a list function in reverse order

(9) enumerate() //Returned is an object, converted into a list and inserted the index value into a tuple

(10) zip(a, b) //returned is an object, use list to return each tuple composed of a sequence of parameters (tuple)

(11) map(fun,iterator) //Mapping the specified sequence according to the provided function and returning a new list containing the return value of each function;

(12) filter(fun,iterator) //Used to filter the sequence to filter out elements that do not meet the conditions, and return an iterator object to return a value of true;

(13) bin(intnumber) //Information into binary form 010101

(14) locals() //Display the current local variable symbol table

(15) issubclass(class,classinfo(tuple)) #Judging whether a class is a subclass of another class

isinstance(object, classinfo #Judging whether it is an instantiated object. If the first parameter is not an object, it will return False. If the second parameter is not a class or a tuple composed of class objects, a TypeError exception will be thrown;

(16) hasattr(obj,name) #Determine whether the attribute exists in the instantiated object

(17) getattr(obj,name,['prompt when the attribute is not found']) #Get the class attribute information, and return the value when found/otherwise return the msg prompt

(18) setattr(obj,name,value) #Set the value of the class object attribute, if it exists, then overwrite/do not exist, then establish the attribute

(19) selattr(obj,name) #Delete attributes in the object

(20) property(fget=None,fset=None,fdel=None,doc=None) #Using properties to set properties, setting defined properties and their parameters is a written method (allowing programmers to easily and effectively manage property access)

Case:

#! /use/bin/python3
# coding utf-8
# Built-in function

#1.( input)/ print
value =input("Please enter a string of characters or values:")print("The value entered is:",value," |Types of:",type(value))

#2.( type)
a ='520'print(type(a))    #<class'str'>print(type(5.2))  #<class'float'>print(type(True))  #<class'bool'>

#3. isinstance(Type value,Types of)=>Type value能匹配上Types of则为True,Otherwise False
print(isinstance(a,str))print(isinstance(12,int))print(isinstance(12.5,float))print(isinstance(True,bool))

#4. Use of assert
>>> assert 3>4//If the program is false, assert an error Traceback(most recent call last):
 File "<pyshell#51>", line 1,in<module>
 assert 3>4
 AssertionError

#5. range()-BIF function generates sequence
print(list(range(5)))  #[0,1,2,3,4]for i inrange(10)://The default is to start from 0 without 10print(i,end=" ")  #0123456789

#6. sorted sorting function/7.reversed
sorted([23,56,2,16,96,12,14])   # [2,12,14,16,23,56,96]list(reversed([23,56,2,16,96,12,14]))   #reversed returns an object,Then use reversed to convert to a list and display the reverse order[14,12,96,16,2,56,23]

#8. enumerate  
list(enumerate([23,56,2,16,96,12,14])) #Enumerate, return the object and then return a (index+Value) list tuple//[(0, 23), (1, 56), (2, 2), (3, 16), (4, 96), (5, 12), (6, 14)]for index,line inenumerate(f): #You can also get the index and the value of each line from the opened file (recommended when the file is large)
 print(index,line)  # 0 #!/usr/bin/python3

#9. zip list correspondence
list(zip([1,2,3],[4,5,6,7]))    #//The lists of a and b correspond one to one[(1, 4), (2, 5), (3, 6)]

#10. map mapping function Note: powerful map()The latter can accept multiple sequences as parameters.
map(lambda x: x **2,[1,2,3,4,5])   #Use lambda anonymous function and map mapping[1,4,9,16,25]list(map(lambda x, y :[x, y],[1,3,5,7,9],[2,4,6,8,10]))  #The packed form is a list instead of a tuple
[[1,2],[3,4],[5,6],[7,8],[9,10]]  

#11. filte filters out 1~The square root of 100 is an integer number#[0,1,4,9,16,25,36,49,64,81]print(list(filter(lambda x: math.sqrt(x)%1==0,range(100))))  

#13. bin binary conversion
bin(255)  #'0b11111111'

#14. locals
>>> locals(){'__name__':'__main__','__doc__': None,'__package__': None,'__loader__':<class'_frozen_importlib.BuiltinImporter'>,'__spec__': None,'__annotations__':{},'__builtins__':<module 'builtins'(built-in)>}

#15. issubclass()Built-in functions of the class.START
classt1:
 pass

classt2(t1):
 noneValue = None  #Null,Equivalent to null in C
 def __init__(self,x=0):
 self.x = x

print(issubclass(t2,t1))  #t2 is a subtype of t1 is true
test =t2(1024)print(isinstance(test,t1))  #True instantiated object test is t1 instantiated object

#16. hasattr Note that the object attribute is to pass in a string
print(hasattr(test,'x'))  #&#39;x&#39; is a property of the test object returns True

#17. getattr Get object attribute value
print(getattr(test,'x'))   #1024print(getattr(test,'e','There is no e attribute in the instantiated object')) #有There is no e attribute in the instantiated object

#18. setattr set object attribute value
setattr(test,e,'Hello world')print(getattr(test,'e','There is no e attribute in the instantiated object')) #hello world

#19. delattr delete object attributes
delattr(test,'e')

#20. property()Use properties to set properties (the method is encapsulated and called again,No matter how you change the method name inside,The interface never becomes)! important
classgetSize:
 def __init__(self,size =0):
  self.size = size
 def getsize(self):return self.size
 def setsize(self,value):
  self.size = value
 def delsize(self):
  del self.size
    
 x =property(getsize,setsize,delsize,"I'm the 'x' property.") #Contains some methods established by this class(Now x is an attribute)

demo =getSize(1024) #Instantiate object
print(demo.x)  #Use the attribute acquisition method to return a value of 1024
demo.x =2048  #Use attributes to set method values
print(demo.x)  #Get the value 2048
del demo.x     #Delete value

Python built-in function example

**Q: What is the difference between isinstance and type? **
A: type() will not consider the subclass to be a parent type, and isinstance() will consider the subclass to be a parent type.

>>> classA:...     pass
>>> classB(A):   #B is a subclass of A
...  pass
>>> isinstance(A(), A)  #True
>>> type(A())== A      #True
>>> isinstance(B(), A)  #True
>>> type(B())== A      #False

0 x01 Python string built-in functions####

(1) capitalize() converts the first character of the string to uppercase.

(2) swapcase() converts uppercase to lowercase and lowercase to uppercase in a string.

(3) lower() converts all uppercase characters in the string to lowercase.
upper() converts lowercase letters in a string to uppercase.

(4) title() returns a "titled" string, which means that all words start with uppercase and the remaining letters are lowercase.

(5) max(str) returns the largest letter in the string str.
min(str) returns the smallest letter in the string str.
len(string) returns the length of the string.

(6) center(width, fillchar) returns a string with the specified width in the center, fillchar is the filled character, and the default is a space.

(7) zfill (width) returns a string of length width, the original string is right-aligned, and the front is filled with 0
ljust(width[, fillchar]) returns a new string with the original string left-justified and filled to the length width with fillchar. The fillchar defaults to a space.
rjust(width,[, fillchar]) returns a new string with the original string right-justified and filled with fillchar (default space) to the length width

(8) count(str, beg= 0,end=len(string)) returns the number of occurrences of str in string, if beg or end is specified, returns the number of occurrences of str in the specified range

(9) find(str, beg=0 end=len(string))
Check if str is contained in the string, if the range beg and end are specified, check if it is contained in the specified range, if it contains, return the starting index value, otherwise return -1
rfind(str, beg=0,end=len(string)) is similar to the find() function, but searches from the right.

(10) index(str, beg=0, end=len(string)) is the same as the find() method, except that if str is not in the string, an exception will be reported.
rindex( str, beg=0, end=len(string)) is similar to index(), but starts from the right.

(11) bytes.decode(encoding=”utf-8”, errors=”strict”)
There is no decode method in Python3, but we can use the decode() method of the bytes object to decode a given bytes object, which can be encoded and returned by str.encode().
encode(encoding=’UTF-8’,errors=’strict’)
Encode the string in the encoding format specified by encoding. If an error occurs, a ValueError will be reported by default, unless errors specify'ignore' or'replace'

(12) startswith(substr, beg=0,end=len(string))
Check whether the string starts with the specified substring substr, if yes, return True, otherwise return False, if beg and end specify values, then check within the specified range.
endswith(suffix, beg=0, end=len(string))
Check whether the string ends with obj, if beg or end is specified, check whether the specified range ends with obj, if yes, return True, otherwise return False.

(13) lstrip() cuts off the spaces or specified characters on the left side of the string.
rstrip() removes the spaces at the end of the string.
strip([chars]) performs lstrip() and rstrip() on the string
(14) expandtabs(tabsize=8) converts the tab symbol in the string to a space, the default number of spaces for the tab symbol is 8

(15) join(seq) takes the specified string as the separator, and merges all the elements (the string representation) in seq into a new string

(16) replace(old, new [, max]) #Replace str1 in the string with str2. If max is specified, the replacement will not exceed max times.

(17) split(str=””, num=string.count(str)) num=string.count(str)) Use str as the separator to intercept the string, if num has a specified value, only num+1 substrings will be intercepted

(18) splitlines([keepends]) is separated by lines ('\r','\r\n', \n') and returns a list containing each line as an element. If the parameter keepends is False, no line breaks are included. If it is True , The newline character is retained.

(19) maketrans() creates a conversion table of character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string, which indicates the character to be converted, and the second parameter is also a string that indicates the target of the conversion.
translate(table, deletechars=””) uses the created character mapping table to convert the characters in the string; converts the characters of the string according to the table given by str (containing 256 characters), and puts the characters to be filtered out to deletechars in

(20) partition(sep) #Split by characters into tuple types

(21) format() #String formatting (keyword parameter key and unknown parameter {0} {1}) replacement field

**Return boolean type: **
(20) isalnum() returns True if the string has at least one character and all characters are letters or numbers, otherwise it returns False.
(21) isalpha() returns True if the string has at least one character and all characters are letters, otherwise it returns False
(22) isdigit() returns True if the string contains only digits, otherwise returns False.
(22) islower() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, it returns True, otherwise it returns False
(23) isnumeric() If the string contains only numeric characters, it returns True, otherwise it returns False
(24) isspace() If the string contains only whitespace, it returns True, otherwise it returns False.
(25) istitle() returns True if the first letter of all words in the string is capitalized and other letters are lowercase, otherwise it returns False.
(26) isupper() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, it returns True, otherwise it returns False
(27) isdecimal() #Check whether the string contains only decimal characters, if it is, it returns true, otherwise it returns false.

#! /usr/bin/python3
# coding:utf-8
# String built-in methods

string ="thisisdemo"print(string.capitalize())    #Capitalize the first letter Thisisdemo
print(string.center(30,'-'))  #Center the specified character,Use the rest-Fill Thisisdemo
print(string.count('i'))      #The number of times the character appears in the string 2

str ="Python programming language"
str_gbk = str.encode("GBK")print(str)   #Character Encoding
print("UTF-8 Encoding:",str.encode("UTF-8"))  # UTF-8 Encoding: b'Python\xe7\xbc\x96\xe7\xa8\x8b\xe8\xaf\xad\xe8\xa8\x80'print("GBK encoding:", str_gbk )  #GBK encoding: b'Python\xb1\xe0\xb3\xcc\xd3\xef\xd1\xd4'print(str_gbk.decode('GBK','strict'))     #Character decoding Python programming language

print(str.endswith('Speak'))  #Judge whether it ends with True
print(str.find('thon'))  #Check if str is included in the string and return the starting index value 2print(str.rfind('thon'))  #Same as above, but to find 2print from the right("1234578".isdigit()) #Check if the strings are all digital trueprint(string.islower())   #If the string contains at least one case-sensitive character
str ="This is String Example...Wow!!!"print(str.title())   #Spell all words in the string with the first letter capitalized This Is String Example...Wow!!!print(str.istitle())  #Whether the first letter of all words is capitalized

print("ABC".lower())  #Convert uppercase to lowercase abc
print("abc".upper())  #Convert lowercase to uppercase ABC

# Create a conversion table for character mapping
intab ="aeiou"
outtab ="12345"
trantab = str.maketrans(intab,outtab)
str ="this is string example....wow!!!"  #th3s 3s str3ng 2x1mpl2....w4w!!!print(str.translate(trantab))  #Use the mapping table to replace the characters in the str string such as i->3

str.maketrans('s','S')     # {115:83}Return Ascii code
str.maketrans('A','a')    # {65:97}Return Ascill Code

print(str.replace('this','demo'))  #String replacement
print(" this is a string ".strip())  #Clear the spaces on both sides and lstrip()/rstrip()print('-'.join("this"))  #Connect the elements in the sequence with the specified characters to generate a new string t-h-i-s
print(str.split(" ")) #Character split return list['this','is','string','example....wow!!!']print("this".zfill(10)) #The original string is right-aligned, and the front is filled with 0 000000this
print("t \r his \n is \n".splitlines())  #according to('\r','\r\n', \n')Split string and return list['t ', ' his ', ' is ']
test ="""
... I love you baby
... vercy
... add string"""
test.splitlines() #['','I love you baby','vercy','add string']'Xiao\tJia\tYu\tPython'.expandtabs(tabsize=2)  #Turn the tab symbol into a space'Xiao  Jia Yu  Python''I test you'.partition('t')                    #Split into tuples('I ','t','est you')"{0} love {1} {2}".format("I","fishc","com")         #  //Location parameter'I love fishc com'"{a} love {b} {c}".format(a="I",b="fishc",c="com")   #  //Keyword parameter'I love fishc com'"{0} love {b} {c}".format("I",b="fishc",c="com")      #//Mixed use#The two can also be mixed, but the keyword parameter must be after the unknown parameter"{{123123213}}".format("Do not print")                      #//'{123123213}'String escaping

Python string example

0 x02 Python list built-in functions####

(1) len(list) the number of list elements
max(list) returns the maximum value of list elements
min(list) returns the minimum value of list elements
list(seq) convert a tuple to a list

Python contains the following methods:
(2) list.append(obj) adds a new object at the end of the list
(3) list.count(obj) count the number of times an element appears in the list
(4) list.extend(seq) append multiple values in another sequence at the end of the list at once (extend the original list with the new list)
(5) list.index(obj) Find the index position of the first match of a value from the list
(6) list.insert(index, obj) inserts the object into the list
(7) list.pop([index=-1]) removes an element from the list (the last element by default), and returns the value of the element
(8) list.remove(obj) removes the first match of a value in the list
(9) list.reverse() Reverse the elements in the list and reorder
(10) list.sort( key=None, reverse=False positive sorting/TRUE reverse sorting) sort the original list
(11) list.clear() Clear the list, empty the list, and leave an Empty list
(12) list.copy() copy list

Code case:

#! /usr/bin/python
# Function: Get list built-in method
dir(list)  #View built-in methods

member =['list1','list2','list3']print("List length:",len(member))

# The list is a big miscellaneous tank that can be compared and some common operators can be performed
list1 =[123]
list2 =[234]print(list1 > list2) #Make logical judgments
list3 =[234]print((list1 < list2)and(list2 == list3))  #Make logical judgments

# List adding method
member.insert(0,'0insert') #Head insertion//member is the object,append()Is a method of the object
member.insert(2,'2insert') #Insert at specified location
member.extend(['list3','list4']) #Add from a newly created list to another list, so extend()The data in must be a list.
member.append(['4apped1','4apped2']) #Insert the list at the end
print(member)

# List delete element
member.remove('2insert') #No need to know the location,Only need to know the element data in the list
del member[0] #Add the index of the list to delete the element on the index,Add a list object to delete the list.print(member.pop()) #The list is stored using the data structure of the stack,So pop()Method to pop the stack,Take the last element from the list to you by default
member.pop(2)  #You can also add index values to pop the stack
print(member,end="\n\n")print(member.count('list3')) #Count the occurrences of elements
print(member.index('list2')) #Element index,Search index index based on element

member.reverse()  #List reordering
print(member,end="\n\n")

# Use sort to sort in the specified way
# sort(func[Specify the sorting algorithm],key[Keywords with algorithm])=>Default algorithm merge sort
list1 =[4,8,10,58,2,6]
list1.sort()print(list1)
list1.sort(reverse=True)  #Or directly use reverse=True  =>The elements in the list must be of the same type
print(list1)

# Clear and copy lists
list2 = member.copy()print(list2) #Copy list
list2.clear() #Clear list return[]print(list2)

Python list case

  1. copy.copy Shallow copy only copies the parent object, not the child objects inside the object.
  2. copy.deepcopy deep copy copy object and its children
# - *- coding:utf-8-*-import copy
a =[1,2,3,4,['a','b']] #Original object
 
b = a #Assignment, pass the reference of the object
c = copy.copy(a) #Object copy, shallow copy
d = copy.deepcopy(a) #Object copy, deep copy
 
a.append(5) #Modify object a
a[4].append('c') #Modify object a['a','b']Array object
 
print 'a = ', a
print 'b = ', b
print 'c = ', c
print 'd = ', d
Output result:
a =[1,2,3,4,['a','b','c'],5]
b =[1,2,3,4,['a','b','c'],5]
c =[1,2,3,4,['a','b','c']]  #Shallow copy append will not modify/But it can be modified
d =[1,2,3,4,['a','b']]       #Deep copy

0 x03 Python collection built-in functions####

(1) add() adds elements to the collection
update() add elements to the collection
(2) clear() remove all elements in the set (clear set())
(10) pop() randomly remove elements
(11) remove() removes the specified element, if obj does not exist in s, an exception will be raised
(6) discard() deletes the specified element in the collection, if obj does not exist in s, it is fine ^_^
(3) copy() copy a collection

(4) s.union(t) | returns the union of two sets, s | t merge operation: s "or" elements in t
(5) s.difference(t) returns the difference of multiple sets, s-t exists in s but does not exist in t
s.difference_update() removes an element from the collection, which also exists in the specified collection. s -= t
(7) intersection() returns the intersection of the set s & t
intersection_update() deletes an element in the collection, which does not exist in the specified collection. s &= t |s includes only members that are shared by s and t
(12) symmetric_difference() returns the set of elements that are not repeated in the two sets, different sets; s ^ t
symmetric_difference_update() removes the same elements in another specified set from the current set, and inserts different elements in another specified set into the current set. s ^= t

(8) isdisjoint() Determines whether the two sets contain the same elements, if not, it returns True, otherwise it returns False.
(9) s.issubset(t) Determines whether the specified set is a subset of the method parameter set. # s <= t, all elements in s are members of t
s.issuperset(t) Determine whether the parameter set of this method is a subset of the specified set # s >= All elements in tt are members of s
(13) fronzeset() freezes a set, the period cannot be added or modified.

Case:

#! /usr/bin/python3
# Function: collection of built-in functions

set1 ={1,2,3,5,6,7}
set2 ={7,11,9,10}
set1.add(8)  #Add collection elements
print("Add elements:",set1)  #Add elements: {1,2,3,5,6,7,8}
set1.update(set2)  #You can directly add the collection to the target collection
print("update:",set1)  #update: {1,2,3,5,6,7,8,9,10,11}

set1 = set2.copy()  #Copy set
print("copy:",set1)    #copy: {9,10,11,7}print("pop remove:",set2.pop())  #随机移除元素  pop remove:9
set2.remove(11)  #Remove specified element,Element does not exist error
set2.discard(10)  #Remove the specified element, no error is reported if the element does not exist
print("remove:",set2)  #remove: {7}

set2.clear()  #Empty collection
print("Empty:",set2)    #Empty: set()

# Subtraction
x ={"apple","banana","cherry"}
y ={"google","microsoft","apple"}
z = x.difference(y)  #That is, the returned collection elements are included in the first collection, but not in the second collection(Method parameters)in.
print(z)  #{'cherry','banana'}

x.difference_update(y)  #Remove the elements contained in both collections (modify directly in the collection)
print("Subtraction",x)  #Subtraction {'cherry','banana'}

# Intersection
x ={1,4,6}
y ={2,1,7}
z = x.intersection(y)print("Intersection",z)   #Intersection {1}

# Union
z = x.union(y)print("Union:",z) #Union: {1,2,4,6,7}

# Yior set (a set that does not exist in both sets)
z = x.symmetric_difference(y)print("Different episodes:",z)

# Determine whether it is a subset
print({"a","b","c"}.issubset({"f","e","d","c","b","a"})) #Determine whether all elements of set x are included in set y
print({"f","e","d","c","b","a"}.issuperset({"a","b","c"}))#Determine whether all elements of set y are included in set x

# Determine whether two sets contain the same elements
print("Is the collection the same:",x.isdisjoint(y))

# Frozen collection (cannot be added or modified)
num =frozenset([1,2,3,4])  #frozenset({1,2,3,4})<class'frozenset'>

Python collection case

0 x04 Python dictionary built-in functions####

(1) str(dict) Output dictionary, expressed as a printable string.
(2) radiansdict.fromkeys(seq[, value]) Create a new dictionary, use the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all the keys of the dictionary
(3) radiansdict.copy() returns a shallow copy of a dictionary
(4) radiansdict.get(key, default=None) returns the value of the specified key, if the value is not in the dictionary, it returns the default value
(5) radiansdict.setdefault(key, default=None) is similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
(6) radiansdict.clear() delete all elements in the dictionary
(7) radiansdict.keys() returns an iterator, which can be converted to a list using list()
(8) radiansdict.values() returns an iterator, which can be converted to a list using list()
(9) radiansdict.items() returns a traversable (key, value) tuple array as a list
(10) radiansdict.update(dict2) Update the key/value pairs of dictionary dict2 to dict, which is to add key/value
(12) pop(key[,default]) Delete the value corresponding to the given key of the dictionary, and the return value is the deleted value.
The key value must be given, otherwise the default value is returned.
(13) popitem() randomly returns and deletes a pair of keys and values in the dictionary (usually delete the last pair).
(11) key in dict If the key is in the dictionary dict, return true, otherwise return false

Case:

#! /usr/bin/python3
# coding:utf-8
# Function: built-in dictionary function
dict1 ={"one":'weiyigeek',"two":"tterdst"}
dict2 =dict.fromkeys(('name','age'),'weiyigeek')print("dictionary:",str(dict1),"Types of:",type(dict1))print("建立dictionary:",str(dict2))print("Name:",dict1.get('one'))print("unknown:",dict1.setdefault('three',"ValueNULL"))print("Key :",list(dict1.keys()))print("Value :",list(dict1.values()))print("dict :",dict1.items()) #dict_items([('one','weiyigeek'),('two','tterdst'),('three','ValueNULL')])

dict1.update({'four':'update'}) #Add key-value pairs
print("Add key-value pairs:",dict1) #{'one':'weiyigeek','two':'tterdst','three':'ValueNULL','four':'update'}print("pop('one') :",dict1.pop('one'))  #Delete the specified key and value and return the value weiyigeek
print("popitem() :",dict1.popitem())  #Delete the last key('four','update')

dict2.clear()print("Empty dictionary:",dict2)  #Empty dictionary: {}

# Member operator
print("Determine if the key is in the dictionary:",'two'in dict1)  # True

Python dictionary case

0 x05 Python file system functions####

(0) open(file,mode,encoding) #Open file name mode format, and encoding, return an f file object
open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
(1) f.close() #Close the file
(2) f.read([size=-1]) #Read size characters from the file, when size is not given or a negative value is given, read all the remaining characters, and then return as a string;
(3) f.readline([size=-1]) #Read and return a line from the file (including the end of the line), if size is defined, return size characters
(4) f.writelines(seq) #Write a list of sequence strings seq to the file, if you need to wrap, you must add the newline character for each line.
(5) f.write(str) write the string str to the file
(6) f.seek(offset, from) #Move the file pointer in the file, offset bytes from from (0 represents the starting position of the file, 1 represents the current position, 2 represents the end of the file)
(7) f.tell() #Return the current position in the file
(8) f.truncate([size=file.tell()]) #The method is used to truncate the file and return the truncated byte length. The default is to intercept the current position of the file pointer (9) file.flush() #Refresh the internal buffer of the file ( At the same time, the buffer is cleared), and the data in the internal buffer is directly written to the file immediately, instead of passively waiting for the output buffer to be written, there is no return value.
(10) file.fileno() #Returns an integer file descriptor (file descriptor FD integer), which can be used in some low-level operations such as the read method of the os module.
(11) file.next() #Return to the next line of the file.
(12) file.isatty() #If the file is connected to a terminal device, it returns True, otherwise it returns False.

# File open mode
' r'Open the file as read-only (default)
' w'Open the file for writing, it will overwrite the existing file
' x'If the file already exists, opening in this mode will cause an exception
' a'Open in writing mode, if the file exists, append writing to the end
' b'Open file in binary mode
' t'Open in text mode (default)
'+' Read and write mode (can be added to other modes)
' U'Universal newline support

open function mode attribute parameter

Case:

#! /usr/bin/python3
# Function: File system

# File reading
file =open('.//python.txt',mode='r+',encoding='utf-8')print(file)  #Pointer

# Return a list,File pointer to the end.print(file.readlines())print("File pointer position:",file.tell())

# Modify the file pointer to point to the initial position
file.seek(0,0)print("File reading",file.read())  #File reading
file.seek(0,0)print("Read line: %s"%(file.readlines()))

# Used to truncate the file and return the truncated byte length,All content after the 10th byte is deleted
file.seek(10)
file.truncate()  #Capture the current pointer position by default
file.seek(0,0)print("Read line: %s"%(file.readlines()))
file.close()  #Close file

f =open("test.txt",'w+',encoding='utf-8')    #Write file

print("The file descriptor is: ", f.fileno()) #The file descriptor is:3

f.write("This is a file write,In order not to garbled, you need to specify utf-8 coding")
f.writelines("File is written as a string")
f.flush()   #Write the data in the buffer to the file/And clear the buffer area (for selective writing)
f.close()

File system example

0 x06 Python magic method summary####

Python’s magic methods are very powerful, but with it comes responsibility; objects are born with some magic methods, they are always surrounded by double underscores, they are everything in object-oriented Python;
If your object implements (overloads) one of these methods, then this method will be called by Python under special circumstances. You can define the behavior you want, and all of this happens automatically.

(1) Basic magic method:

__ new__(cls[,...])1.  __new__Is the first method called when an object is instantiated
2. Its first parameter is this class, and the other parameters are used to pass directly to__init__method
3. __ new__Decide whether to use the__init__Method because__new__You can call the constructor of other classes or directly return other instance objects as instances of this class, if__new__No instance object is returned, then__init__Will not be called
4. __ new__Mainly used to inherit an immutable type such as a tuple or string
__ init__(self[,...])Constructor, the initialization method that is called when an instance is created
__ del__(self)Destructor, the method to be called when an instance is destroyed
__ call__(self[, args...])Allow an instance of a class to be called like a function: x(a, b)Call x.__call__(a, b)__len__(self)Defined as len()Behavior when called
__ repr__(self)Defined as repr()Behavior when called
__ str__(self)Defined when str()Behavior when called
__ bytes__(self)Defined as bytes()Behavior when called
__ hash__(self)Define when to be hashed()Behavior when called
__ bool__(self)Defined as bool()Behavior when called, should return True or False
__ format__(self, format_spec)Define when formatted()Behavior when called
__ bases__(self)   #Supplement, show its base class

(2) Related attributes

__ getattr__(self, name)Define the behavior when the user tries to get a non-existent attribute
__ getattribute__(self, name)Define the behavior when the properties of the class are accessed
__ setattr__(self, name, value)Define the behavior when an attribute is set
__ delattr__(self, name)Define the behavior when an attribute is deleted
__ dir__(self)Define when dir()Behavior when called
__ get__(self, instance, owner)Define the behavior when the value of the descriptor is obtained
__ set__(self, instance, value)Define the behavior when the value of the descriptor is changed
__ delete__(self, instance)Define the behavior when the value of the descriptor is deleted

(3) Comparison operator

__ lt__(self, other)Define the behavior of the less than sign: x<y calls x.__lt__(y)__le__(self, other)Define the behavior of less than or equal signs: x<=y calls x.__le__(y)__eq__(self, other)Define the behavior of the equal sign: x==y calls x.__eq__(y)__ne__(self, other)Define the behavior of unequal signs: x!=y calls x.__ne__(y)__gt__(self, other)Define the behavior of greater than sign: x>y calls x.__gt__(y)__ge__(self, other)Define the behavior of greater than or equal to: x>=y calls x.__ge__(y)

(4) Arithmetic operator

__ add__(self, other)Define the behavior of addition:+__sub__(self, other)Define the behavior of subtraction:-__mul__(self, other)Define the behavior of multiplication:*__truediv__(self, other)Define the behavior of true division:/__floordiv__(self, other)Define the behavior of integer division://__mod__(self, other)Define the behavior of the modulo algorithm:%__divmod__(self, other)Define when divmod()Behavior when called, the return value is a tuple(a//b,a%b)__pow__(self, other[, modulo])Define when to be powered()Call or**Behavior during operation
__ lshift__(self, other)Define the behavior of bitwise left shift:<<__rshift__(self, other)Define the behavior of bitwise right shift:>>__and__(self, other)Define the behavior of bitwise AND operation:&__xor__(self, other)Define the behavior of bitwise XOR operation:^__or__(self, other)Define the behavior of bitwise OR operation:|

(5) Inverse operation

__ radd__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rsub__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rmul__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rtruediv__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rfloordiv__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rmod__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rdivmod__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rpow__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rlshift__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rrshift__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rand__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ rxor__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)
__ ror__(self, other)(Same as above, it is called when the left operand does not support the corresponding operation)

(5) Incremental assignment operation

__ iadd__(self, other)Define the behavior of assignment addition:+=__isub__(self, other)Define the behavior of assignment subtraction:-=__imul__(self, other)Define the behavior of assignment multiplication:*=__itruediv__(self, other)Define the behavior of assigning true division:/=__ifloordiv__(self, other)Define the behavior of assigned integer division://=__imod__(self, other)Define the behavior of the assignment modulo algorithm:%=__ipow__(self, other[, modulo])Define the behavior of assignment exponentiation:**=__ilshift__(self, other)Define the behavior of the assignment bitwise left shift:<<=__irshift__(self, other)Define the behavior of the assignment bitwise right shift:>>=__iand__(self, other)Define the behavior of assignment bitwise AND operation:&=__ixor__(self, other)Define the behavior of assignment bitwise XOR operation:^=__ior__(self, other)Define the behavior of assignment bitwise OR operation:|=

(6) Unary operator

__ pos__(self)Define the behavior of positive signs:+x
__ neg__(self)Define the behavior of the negative sign:-x
__ abs__(self)Defined as abs()Behavior when called
__ invert__(self)Define the behavior of bitwise negation:~x

(7) Type conversion

__ complex__(self)Defined as complex()Behavior at call time (requires proper value to be returned)
__ int__(self)Defined as int()Behavior at call time (requires proper value to be returned)
__ float__(self)Define when to be float()Behavior at call time (requires proper value to be returned)
__ round__(self[, n])When defined as round()Behavior at call time (requires proper value to be returned)
__ index__(self)1.When the object is applied in the slice expression, implement the shaping coercion
2. If you define a custom numeric type that may be used in slicing,You should define__index__
3. in case__index__Is defined, then__int__Also needs to be defined and return the same value

(8) Context management (with statement)

__ enter__(self)1.Define the initialization behavior when using the with statement
2. __ enter__The return value of is bound by the target of the with statement or the name after as
3.__ exit__(self, exc_type, exc_value, traceback)1.Define what the context manager should do when a code block is executed or terminated
2. Generally used to handle exceptions, clean up work, or do routine work after some code blocks are executed

(9) Container type

__ len__(self)(Returns the number of elements in the container-There is an explanation before)
__ getitem__(self, key)Define the behavior of obtaining the specified element in the container, equivalent to self[key]__setitem__(self, key, value)Define the behavior of the specified element in the setting container, equivalent to self[key]= value
__ delitem__(self, key)Define the behavior of deleting the specified element in the container, equivalent to del self[key]__iter__(self)Define the behavior when iterating the elements in the container
__ reversed__(self)Defined when reversed()Behavior when called
__ contains__(self, item)Define the behavior when using the membership test operator (in or not in)

Case:

classt1:
 def t1print(self):print('t1')classt2:
 def t2print(self):print('t2')classt3(t1,t2):
 pass

print(t3.__bases__)  #Display its base class information(<class'__main__.t1'>,<class'__main__.t2'>)

0 x07 Python standard exception summary####

Ctrl + D  #EOFError
Ctrl + C  #KeyboardInterrupt

###### Python standard exception summary###############
AssertionError assertion statement (assert) failed
AttributeError Attempt to access unknown object attribute
EOFError User input file end flag EOF (Ctrl+d)
FloatingPointError floating point calculation error
GeneratorExit	generator.close()When the method is called
ImportError when importing a module fails
IndexError Index is out of the range of the sequence
KeyError Find a keyword that does not exist in the dictionary
KeyboardInterrupt user input interrupt key (Ctrl+c)
MemoryError Memory overflow (memory can be released by deleting the object)
NameError tries to access a variable that does not exist
NotImplementedError method not yet implemented
OSError An exception generated by the operating system (for example, opening a file that does not exist)
OverflowError Numerical operation exceeds the maximum limit
ReferenceError weak reference (weak reference) attempts to access an object that has been reclaimed by the garbage collection mechanism
RuntimeError General runtime error
StopIteration iterator has no more values
SyntaxError Python syntax error
IndentationError Indentation error
TabError Tab and space mixed use
SystemError Python compiler system error
SystemExit Python compiler process is closed
TypeError invalid operation between different types
UnboundLocalError accesses an uninitialized local variable (a subclass of NameError)
UnicodeError Unicode-related errors (a subclass of ValueError)
UnicodeEncodeError Unicode encoding error (subclass of UnicodeError)
UnicodeDecodeError Unicode decoding error (subclass of UnicodeError)
UnicodeTranslateError Unicode conversion error (subclass of UnicodeError)
ValueError passed an invalid parameter
ZeroDivisionError divide by zero

# The following is the hierarchy of Python&#39;s built-in exception classes:
BaseException
+- - SystemExit
+- - KeyboardInterrupt
+- - GeneratorExit
+- - Exception
  +- - StopIteration
  +- - ArithmeticError
  |+- - FloatingPointError
  |+- - OverflowError
  |+- - ZeroDivisionError
  +- - AssertionError
  +- - AttributeError
  +- - BufferError
  +- - EOFError
  +- - ImportError
  +- - LookupError
  |+- - IndexError
  |+- - KeyError
  +- - MemoryError
  +- - NameError
  |+- - UnboundLocalError
  +- - OSError
  |+- - BlockingIOError
  |+- - ChildProcessError
  |+- - ConnectionError
  ||+- - BrokenPipeError
  ||+- - ConnectionAbortedError
  ||+- - ConnectionRefusedError
  ||+- - ConnectionResetError
  |+- - FileExistsError
  |+- - FileNotFoundError
  |+- - InterruptedError
  |+- - IsADirectoryError
  |+- - NotADirectoryError
  |+- - PermissionError
  |+- - ProcessLookupError
  |+- - TimeoutError
  +- - ReferenceError
  +- - RuntimeError
  |+- - NotImplementedError
  +- - SyntaxError
  |+- - IndentationError
  |+- - TabError
  +- - SystemError
  +- - TypeError
  +- - ValueError
  |+- - UnicodeError
  |+- - UnicodeDecodeError
  |+- - UnicodeEncodeError
  |+- - UnicodeTranslateError
  +- - Warning
   +- - DeprecationWarning
   +- - PendingDeprecationWarning
   +- - RuntimeWarning
   +- - SyntaxWarning
   +- - UserWarning
   +- - FutureWarning
   +- - ImportWarning
   +- - UnicodeWarning
   +- - BytesWarning
   +- - ResourceWarning

Recommended Posts

Python3 built-in function table.md
Python built-in function -compile()
Python enumerate() function
Python function buffer
Python3 built-in module usage
Python custom function basics
Join function in Python
Python function basic learning
Python data analysis-apply function
Python Print print timer function
Python defines a function method
Python high-order function usage summary!
Python realizes online translation function
Python tornado upload file function
Python magic function eval () learning
How Python implements FTP function
Python implements image stitching function
Python high-order function usage summary!
Python telnet login function implementation code
Python| function using recursion to solve
How Python implements the mail function
Why doesn&#39;t Python support function overloading?
Is there function overloading in python
Learning Python third day one-line function
Python function definition and parameter explanation
Python ATM function implementation code example
Python implements AI face change function
Python realizes image recognition car function
Python implements ftp file transfer function
Python realizes udp transmission picture function
How Python implements the timer function
How to run id function in python
What is the id function of python
What is an anonymous function in Python
Comprehensive summary of Python built-in exception types
How does python call its own function
python3 realizes the function of mask drawing
What is the function body of python
Is there a helper function in python