Python Common standards Library

Source: Internet
Author: User
Tags first string mutex thread class wrapper

-------------------system built-in function-------------------
1. String
Str= ' This is a string data test data ' corresponding
Str[0]: Gets the character labeled 0 in the STR string.
STR[3]: Gets the character labeled 3 in the STR string.
Str[0:3]: Gets the string in the string from subscript 0 to subscript 3.

Str.find (): Returns whether the specified string data information exists in the specified STR string, returns the subscript for the first letter of the string if it exists, and returns 1 if it does not exist. Str.index (): Returns whether the specified string data information exists in the specified str string, or returns the subscript for the first letter of the string if there is no exception handling error. Str.count (): Returns the number of information in the specified STR string for the presence of the found string. Len (str): Returns the total length of the character for the specified str string, or 0 if the string is empty. Str.replace (' Replace before character ', ' replace character ', specify number of substitutions): Specifies the substitution of the specified character data in the STR string and returns the replaced data. Str.split ("", Number of cuts): Cuts the specified string, returns the data information of the string list after being cut, and the maximum number of cuts by default if the number of cuts is not filled. Str.capitalize (): capitalizes the first character of a specified str string. Str.startswith (Match string data): Returns the Boolen type, matching whether the specified STR string begins with the specified string data. Str.endswith (Match string data): Returns the Boolen type, matching whether the specified str string ends with the specified string data. Str.lower (): A uniform lowercase conversion of the specified string data information and returns the converted data. Str.upper (): Converts the specified string data information into a uniform uppercase conversion and returns the converted data. Str.ljust (Specifies the length of the string returned): Returns a string that specifies str for left alignment, and a space supplement to the right if the STR string is less than the specified length. Str.rjust (Specifies the length of the string returned): Returns a string that specifies str for right alignment, and a space supplement to the left if the str string length is less than the specified length. Str.center (the length of the string to be returned): Returns a string that will make an intermediate alignment of STR and, if the STR string is less than the length specified, a complementary operation of spaces on both sides. Str.lstrip (): Returns the string, removing the left space. Str.rstrip (): Returns a string that removes the trailing space. Str.rfind (): Similar to the Find function, searches from the right of the specified string, returning the index of the first character of the found string. Str.rindex (): Similar to the index function, starting from the left side of the specified STR string, returns the string index of the first string found. Str.partition (Specifies the segmented wordString): From the specified str string, look for the set of split strings, return a list containing the preceding part of it, itself and its later part; If the string match is unsuccessful, it returns itself and two null characters. Str.rpartition (Specifies the split string): Similar to the partition function, except that the specified split string is searched from the right. Str.splitlines (): Row split, return a list, save each row of data as an element. Str.isdigit (): Returns the Boolen type, judging whether the data in the specified STR string is a letter or a number. Str.isalpha (): Returns the Boolen type, judging whether the data in the specified str string is a pure letter. Str.isalnum (): Returns the Boolen type, judging whether the data in the specified str string is a pure number. Str.isspace (): Returns the Boolen type, judging whether the data in the specified STR string contains only spaces. Str.isupper (): Returns the Boolen type, judging whether the data in the specified STR string is pure uppercase. Str.islower (): Returns the Boolen type, judging whether the data in the specified STR string is in plain lowercase. Mystr.join (str): Splicing the data in the class table mystr according to the specified STR string; Returns the string data information after stitching. Print ("%0.1f", Float (result*1.0)): Converts the floating-point number and prints the data print after the decimal point ("%d*%d=%d"% (j,i,i*j), end= "): Ends the last line break

The underlying operation for the

2, file stream
File stream:
F=open (' filename ', ' access Mode '), if f: Returns the Boolen type, and determines whether the file is open.
W: Open a file for writing only, overwrite if the file already exists, or create a new file if the file does not exist.
R: Open the file as read-only; the pointer to the file will be placed at the beginning of the file; This is the default mode.
A: Opens a file for appending, and if the file already exists, the file pointer will be placed at the end of the file, meaning that the new content will be written to the existing content. If the file does not exist, create a new file to write to.

 RB: Opens a file in binary format for read-only, and the file pointer will be placed at the beginning of the file. This is the default mode. WB: Opens a file in binary format for writing and overwrites the file if it already exists. Creates a new file if the file does not exist. AB: Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content is written to the existing content, and if the file does not exist, a new file is created for the write operation. r+: Open a file for reading and writing, and the file pointer will be placed at the beginning of the file. w+: Open a file for read-write or overwrite it if the Karma file already exists. If the file does not exist, create a new file A +: Opens a file for read-write, or if the file exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write. rb+: Opens a file in binary format for read-write; The file pointer will be placed at the beginning of the file. wb+: Opens a file in binary format for read-write or overwrite if the file already exists. If the file does not exist, create a new file. ab+: Opens a file in binary format for appending, if the file already exists, the file pointer will be placed at the end of the file, and if the file does not exist, create a new file to read and write. F.close (): Closes after the file stream operation has ended. F.wirte (write content): Writes the specified content to the file after the file is opened. F.read (length of read data): Use read to read the specified length of data from a file and move the pointer over this data; Read all data by default. F.readline (): reads the information from one row of data in the file and moves the next line of the pointer. F.readlines (): reads the data information information for the entire file, returns a list of information for each element in the list that is a row of data. F.tell (): View the current position, which is the position of the pointer. Seek (Offset,from): Position the pointer to a location from: direction 0: Indicates the beginning of the file. 1: Indicates the current location of the file. 2: Represents the end of the file. Offset: Offsets test F.seek (5,0): Start of file, offset backward 5 positions F.seek ( -3,2): End of file, offset forward 3 positions 

3, list, dictionary, tuple action
1, List:
strlist=[']: list creation.
str= ' string '
newstr= ' new string '.
Strlist.append: Adds an operation to the list data information.
Strlist[0]=newstr: A list Specifies the modification of the element data information according to the subscript
Str in strlsit: Returns the Boolen type, specifying whether the string information exists in the list.
for item in Strlist: A traversal of the list data, item is the element value
del strlist[0]: Deletes the specified list element according to the list subscript.
Strlist.pop (): Deletes the data information for the last element of the list.
Strlist.remove (' Value of element '): The delete operation is based on the value of the element.

2、字典:    修改元素:根据Key值进行修改    添加元素:infor[‘age‘]=18    删除元素:del    清空字典中的数据信息:infor.clear3、字典的常见操作    dic={1:‘xiaohao‘,2:‘xiaodong‘}:创建一个字典对象。    dic.keys():获取字典所有对应的键,以列表的形式进行返回。    dic.valuses():获取字典所有对应的值,以列表的形式进行返回。    dic.items():获取字典中的键值数据,以列表的形式返回,每个元素都一个元组,分别存放着键和值。    dic.has_key(1):返回boolen类型,判断键值是否存在4、元组:    tuple=(1,2,3,4,5):创建一个元组。    tuple[2]:根据下标读取到第三个元素。    tuple[-2]:根据下标读取到倒数第二个元素。    tuple[1:]:截取元组第二个元素到最后。    cmp(tuple1,tuple2):比较两个元组中的元素。    max(tuple):返回元组中元素的最大值。    min(tuple):返回元组中元素的最小值。    tuple(seq):将列表转换为元组。5、运算符操作列表、字典、元组的技巧:    1、len((1,2,3,4)):获取到元组中元素的个数。    2、(1,2,3,4) +(1,2,3,4,5) ;进行两个元组的合并,获取到一个新的元组。    3、[‘Hi‘]*4:创建一个新的列表,并将列表中的数据进行复制四次。    4、1 in (1,2,3,4):判断元素是否存在;返回boolen类型。

4. Abnormal capture
Definition: Some error actions cause the program not to run correctly
Exception capture:
Try
Except (nameerror,ioerror), Result:
Print (Result) #返回具体的错误信息
Else
Print ("I am Else")
Finally
Print ("I am Finally")

5. Range: Get
1. Help (range):
Range (stop), List of integers
Range (start, stop[, Step), List of integers
2, Parameter analysis:
1. Start: Counting starts from start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5).
2. Stop: Ends with stop, but does not include stop. For example: Range (0, 5) is [0, 1, 2, 3, 4] without 5.
3, Step: The distance of each jump, the default is 1. For example: Range (0, 5) is equivalent to range (0, 5, 1).
3. Example:
A = range (5)
List (a)

6. Map: function
1. Help (map):
Map (...)
Map (function, sequence[, sequence, ...]) list
2, Parameter analysis:
1, function: is a functional
2, Sequence: is one or more sequences, depending on the function requires several parameters
3. The return value is a list
3. Syntax:
Each element in the parameter sequence calls a function, which returns a list containing the return value of each function.
4. Example
#函数需要一个参数
Map (Lambda x:x*x, [1, 2, 3])
[1, 4, 9]

    #函数需要两个参数    map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6])    [5, 7, 9]    #函数为None,相当于合并参数为元祖    map(None, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])    [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]    #两个序列参数个数不一致时,个数少的补None    map(None, [1, 3, 5, 7, 9], [2, 4, 6])    [(1, 2), (3, 4), (5, 6), (7, None), (9, None)]

7. Filter: function
1. Help (Filter):
Filter (...)
Filter (function or None, sequence), list, tuple, or string

    Return those items of sequence for which function(item) is true.  If    function is None, return the items that are true.  If sequence is a tuple    or string, return the same type, else return a list.2、参数分析:    1、function:接受一个参数,返回布尔值True或False    2、sequence:序列可以是str,tuple,list3、语法    filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。返回值的类型和参数sequence的类型相同4、示例    filter(lambda x: x%2, [1, 2, 3, 4])    [1, 3]    filter(None, "she")    ‘she‘

8. Reduce: function
1. Help (reduce):
Reduce (...)
Reduce (function, sequence[, initial]), value

        Apply a function of two arguments cumulatively to the items of a sequence,        from left to right, so as to reduce the sequence to a single value.        For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates        ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items        of the sequence in the calculation, and serves as a default when the        sequence is empty.2、参数分析:    1、function:该函数有两个参数    2、sequence:序列可以是str,tuple,list    3、initial:固定初始值3、语法    reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。 第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial 作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。 注意function函数不能为None。4、示例    reduce(lambda x, y: x+y, [1,2,3,4])    10    reduce(lambda x, y: x+y, [1,2,3,4], 5)    15    reduce(lambda x, y: x+y, [‘aa‘, ‘bb‘, ‘cc‘], ‘dd‘)    ‘ddaabbcc‘

9. Sorted: function
1. Help (sorted):
Sorted (...)
Sorted (iterable, Cmp=none, Key=none, Reverse=false)--New sorted list
2, Parameter analysis:
To customize the CMP comparison function, return three cases:
X<y Return-1
X>y return 1
X==y return 0
3. Example
def cmp_ignore_case (S1, S2):
u1 = S1.upper ()
U2 = S2.upper ()
If U1 < u2:
Return-1
If U1 > U2:
Return 1
Return

-------------------System library functions to help document Find-------------------
1, library function: print (), raw_input () system to call the library function

2、用户自定义函数:如果系统中,没有需要的功能,那么此时就需要自己开发一个,这就是自定义函数3、ipython下:    dir(包名):查看该包下的对应的函数信息    help(包名):查看该包中的分装的函数信息    包名.path:可以获取到指定包对应的文件路径

-------------------Builtins: The built-in function is loaded by default-------------------

-------------------OS: Operating System Interface-------------------
Import OS reference package for system
Os.name (): Judging the platform that is now being used, widows returns ' NT '; Linux returns ' POSIX '.
OS.GETCWD (): Gets the current work directory.
Os.listdir (): Specifies all file and directory names under all directories.
Os.remove (): Deletes the specified file.
Os.rmdir (): Deletes the specified directory.
Os.mkdir (): Create a directory, only one layer can be established.
Os.makedirs (): Recursively create a directory.
Os.path.isfile (): Determines whether the object is a file. Yes returns true, otherwise false.
Os.path.isdir (): Determines whether the specified object is a directory. is true, otherwise false.
Os.path.exists (): Verifies that the specified object exists. is true, otherwise false.
Os.path.split (): Returns the directory and file name of the path.
OS.GETCWD (): Gets the current work directory.
Os.system (): Executes the shell command.
Os.chdir (): Changes the directory to the specified directory.
Os.path.getsize (): Gets the size of the file, if it is a directory, returns 0.
Os.path.abspath (): Gets the absolute path.
Os.path.join (path,name): Connection directory and file name.
Os.path.basename (PATH): Returns the file name.
Os.path.dirname (PATH): Returns the file path.

-------------------the operating environment of the Sys:python itself-------------------
Import SYS refers to the package of the system
Sys.stdin
SYS.ARGV: Gets the corresponding parameter information when the file is executed

-------------------functools: Common Tools-------------------
1. Concept:
Functools is python2.5 and some tool functions are placed in this package.

2, Operation: 1, import Functools: Refer to the corresponding Package 2, dir (functools): View the corresponding tool function in the package 1, partial function (partial function): 1, Concept: Set some parameters of a function default value, return a    New function, it would be easier to call this new function. 2. Example: Import Functools def showarg (*args, **kw): print (args) print (kw) p1=funct Ools.partial (Showarg) p1 () p1 (4,5,6) p1 (a= ' python ', b= ' Itcast ') p2=functools.partial (sh Owarg, a=3,b= ' Linux ') P2 () P2 (P2 ' python ', a= ' b= ') 2, Itcast function: 1, Concept: When using adorners, there are some details that need to be To be noticed. For example, a decorated function is actually a different function (function names and other functions will change). Python's Functools package provides an adorner called wraps to eliminate such side effects. 2, Example: Import functools def note (func): "Note functi On "@functools. Wraps (func) def wrapper ():" Wrapper function "Print (' No Te something ') return func () return wrapper @note def test (): "Test fun ction "Print (' I am Test ') test () print (test.__doc__)

-------------------JSON: Encode and decode JSON objects-------------------

-------------------Logging: Logging, debugging-------------------

-------------------fork/multiprocessing: Multi-process-------------------
Import OS:

  1, pid=os.fork (): When the program executes to Os.fork (), the operating system creates a new process (child process), and then copies all the information of the parent process into the child process, and the parent and child processes get a return value from the fork () function.    This value must be 0 in the process, and the parent process is the ID number of the child process; the main: Fock () function can only be run on Unix/linux/mac, Windows cannot run.        Import OS # Note that the fork function, only runs on Unix/linux/mac, Windows can not PID = Os.fork () if pid = = 0:print (' haha 1 ') Else: Print (' Haha 2 ') os.getpid (): Gets the PID number of the current process os.getppid (): Gets the PID number 2 to the parent process, the second way that the process is created: from multiprocessing import Process: references the corresponding package. P=process (target=run_proc,args= (' Test ',)): invokes the Process class to create the procedure object. The method to be implemented for the parameter target assignment process, which passes the corresponding parameter to the parameter args assignment method. P.start (): Turns on execution of the corresponding process action. P.join (): Waits for the current process to finish executing and can wait for the child process to end before continuing to run down, typically for inter-process synchronization. Multiprocessing.cpu_count (): Gets the number of cores of CPU used by the process execution. Pipe=multiprocessing. Pipe (): The pipeline realizes the communication between processes. A pipeline has two ports, pipe[0] and pipe[1]pipe[0].send (data added to the pipeline): adding operations to the pipeline. PIPE[0].RECV (): Remove the corresponding data information from the pipeline. 3, from multiprocessing import process,queue: Apply the corresponding package, in order to achieve the communication between processes; One of the two ends of the pipeline is responsible for writing data to it, and one is responsible for reading the data outside. Q=queue (): Creates a queue object. Q.put (data information to be added to the queue): Add the data you have made to the queue. Q.get (True): The queue data information to extract from the queue. Q.empty (): Determines whether the current queue is empty. 

-------------------Threading: Multithreaded-------------------
1, the first mode of threading application The thread module is the lower-level module
Import Thread: references the corresponding module package.

    Thread.start_new_thread (Defname, ()) creates a new thread to open, the first parameter is the method to be executed by the new thread, the second parameter is the tuple pass execution method corresponding to the required parameters; Note: Python tuples are required for one (element,)    An element plus a ', ' is represented.    Thread.exit_thread (): The main thread calls the method to represent all the end operations of the threads, and the child thread represents the end operation that implements the current child thread by calling the Exit.thread () method. Thread.Join (): The Join () method is also available in the thread class of Python so that one thread can wait for another thread to execute before it runs. This method can also set a timeout parameter to avoid endless waiting. Because two threads are completed in sequence and look like a thread, it is called a thread's merge Thread.setdaemon (True): By default the main thread exits waiting for the end of the child thread, if you want the main thread to not wait for the child thread, you can set the child thread to be the background thread, the main thread exits, The child thread ends.    2, threading application of the second mode threading module is the thread module is a certain package, can be more convenient for our use.    Import Threading: Reference the corresponding module package. Mythread=threading.    Thread (target=defname,args= (' Alice ')) creates a thread, target assigns a method to execute the thread, and args copies the parameter information required by the execution method.    Mythread.start (): Thread starts execution. Num=len (threading.enumerate): View the number of threads currently executing. 3. The third way of threading application is to create a thread class that inherits the base class threading.    Thead; overrides the Def run (self) of the base class by writing the program that the thread is executing in the method. Class MyThread (threading. Thread): Create a thread class to create a base class constructor Def __init__ (self,name,time): Threading.    thread.__init__ (self,name= ' can copy the name of a thread ') Mythread=mythread (): Creation of a Thread object. Mythread.start (): the thread executes. 4. LOC is defined in the threading moduleK () class, can handle locking conveniently. Mutex=threading.    Lock (): Creation of the mutex object. If Mutex.acquire ([blocking]): Locks, returns true after a lock succeeds, locking method acquire () can have a blocking parameter.    If blocking is set to true, the current thread is blocked until the lock is acquired (true if not specified), and if the setting blocking is false, the current thread does not block. Mutex.release (): The release of the lock after executing the program content. 5, support the same thread multiple requests to the same resource, Python provides a reentrant lock. Rlock object, while maintaining a lock and a counter variable, counter variable storage acquire the number of times, so that resources can be acquire many times, until all the acquire in a thread is release, Other threads can get the resource mutex=threading.    Rlock (): Creates a reentrant lock object.    Mutex.acquire (): Lock. Mutex.release (): to release.    6. The condition object provided by Python provides support for complex thread synchronization problems; condition is called a conditional variable; condition maintains a lock and a waiting pool. Con=threading.    Condition (): Creates a conditional variable object, can accept a Lock/rlock object as a parameter, or, if not specified, creates a Rlock Con.acquire () by default: Locks.    Con.wait (): The thread frees the condition internal lock and enters the blocked (blocked) state while recording the thread in the waiting pool.    Con.notify (): The Condition object picks a thread from the waiting pool and notifies it to call the acquire method to try to fetch the lock. Con.notifyall (): Condition object notifies all threads in the waiting pool, attempting to acquire an internal lock.    The role prevents some threads from ever being in a state of silence.    Con.release (): to release. Threading. An event can be a thread that waits for notifications from other threads. It has a built-in flag with an initial value of false. The thread enters the wait state through the wait () method until another thread dispatches the set () method to set the built-in labelLog is set to True, the event notifies all waiting states that a thread replies to run.    You can also use the Isset () method to query the current value of the built-in state of the event object. Event=threading.    Event (): Creates the corresponding Envent object. def __init__ (self,threadname,event): self.threadevent=event: Refactoring corresponds to threading.    The __init__ method in the thread base class.    Self.threadEvent.wait (): Causes the thread to enter a wait state. Event.set (): Starts the waiting thread in the waiting pool.

-------------------Queue: Queues-------------------
From queue import queue: references the corresponding module package.
Queue=queue (): Creates a queue object.
Queue.qsize (): Gets the number of elements in the queue.
Queue.put (data added to the queue): Add elements to the queue.
Queue.set (): Removes the element from the queue.
Queue.empty (): Determines whether the queue is empty.

-------------------Copy: Copy-------------------

-------------------Time:-------------------

-------------------datetime: Date and Time-------------------

-------------------Calendar: Calendars-------------------

-------------------hashlib: Encryption Algorithm-------------------

-------------------random: Generates a stochastic number-------------------
Import random: Reference the corresponding package
Random.random (): The default is to obtain data information randomly from 0 to 1.
Random.uniform (1,5): 1 to 5 randomly get the corresponding value, including the fractional part.
Random.randint (10.50): 10 to 50 correspond to randomly obtained corresponding integers
Random.randrange (0,51,2): 0 to 51 corresponds to random acquisition of the corresponding multiples of 3

-------------------Re: string regular match-------------------
Import re: reference the corresponding package
Result=re.match (regular expression, string to match) : The corresponding data information is matched by a regular matching operation from the first character backwards.
Result.group (): If the previous step matches the data, you can use the group method to extract the data.
Result=re.search (the regular expression, the string to match): The matching action is followed backwards from the first character that is matched to.
Result==none: Determines whether the obtained book data is empty.
Re.search (R ' \d+ ', ' my hight 177 cm '). Group (): matches the first data in the specified string that matches the regular expression (only one).
Re.findall (R ' \d+ ', ' my hight 177 cm my weight kg '): matches all valid data in the specified string that match the regular expression and returns as a list.
Re.sub (R ' \d+ ', ' + ', ' my high 177 cm '): Replaces the matched data, parameters: corresponding regular expression, data to be replaced, matching data;

方法一:#coding=utf-8import reret = re.sub(r"\d+", ‘998‘, "python = 997")print ret返回结果:998方法二:#coding=utf-8import redef add(temp):    strNum = temp.group()    num = int(strNum) + 1    return str(num)ret = re.sub(r"\d+", add, "python = 997")print retret = re.sub(r"\d+", add, "python = 99")print ret返回结果:100re.split(r‘:| ‘,‘address:beijing [email protected]‘):根据匹配进行切割字符串,并返回一个列表。案例:根据:或空格进行字符串的切割操作,结果:[‘address‘,‘beijing‘,‘[email protected]‘]

-------------------socket: Standard BSD Sockets API-------------------

-------------------shutil: File and Directory Management-------------------

-------------------Glob: Search-------------------based on file wildcard characters

-------------------Keyword: keywords-------------------
Import Keyword: reference the corresponding package
Keyword.kwlist (): Gets a list of the corresponding keywords in python that are stored in the list

Python Common standards Library

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.