Novice when doing the writing code easy to jam, especially when the function of contact and other knowledge more, after seeing demand often don’t know if I should use what method to implement it, realize the logic may be you have, but how to forget, what function it is knowledge reserves is insufficient, you can’t remember which function has what effect, natural confused about.

In recent days, I have organized some common Python functions, from the most basic input and output functions to re, a total of more than 100 commonly used functions, so that you can quickly memorize them. You can quickly go through them every day and deepen them when you use them. Slowly you will get rid of the problem of writing code.

While the emphasis in self-learning programming is more on understanding and actually coding, there are some things you need to keep in mind or you won’t get anywhere writing code. For starters, memorizing frequently used functions is a good way to develop quickly.

1. Basic functions

The serial number function instructions
1 print() The output
2 input() The input
3 int() Turn the integer
4 float() Turn floating-point
5 str() Turn the string
6 type() Returns the type of the object
7 isinstance() Return Boolean (True,False)

Example: Convert a floating point value to a string and print the converted data type

f = 30.5
ff = str(f)
print(type(ff))

Class 'STR'
Copy the code

2. Process control

The serial number function instructions
1 If statement: Execute 1 conditional
2 If condition: code block 1 else: code block 2 conditional
3 while Judgment cycle
4 for Count cycle
5 range() A range function that controls the start position, end position, and step size
6 break Jump out of the loop
7 continue Skip this loop and the next loop continues

Case: Judge the score according to the score input by the user. When the score is lower than 50, it will prompt “your score is lower than 50”; when the score is 50 and 59, it will prompt “your score is around 60”; when the score is greater than or equal to 60, it will be regarded as passing; when the score is 80 and 90, it will be regarded as excellent; when the score is greater than 90, it will be regarded as very excellent.

s = int(input("Please enter the score :"))
if 80 >= s >= 60:
    print("Pass")
elif 80 < s <= 90:
    print("Good")
elif 90 < s <= 100:
    print("Very good.")
else:
    print("Fail")
    if s > 50:
        print("Your score is in the 60s.")
    else:
        print("Your score is below 50.")
        
Copy the code

List 3.

The serial number function instructions
1 append() Add an object to the list and add it to the end
2 Extend (iterable) Add the data from the iterable to the list separately and to the end
3 Insert (subscript, object) Adds an object to the specified subscript position
4 clear() Empty the list
5 pop() Deletes the element specified by subscript, or the last element if no subscript is added
6 Remove (object) Deletes the specified object
7 del Deletes a variable or specifies the value of the following table
8 copy() Shallow copy
9 Count (object) Returns the number of occurrences of the object in the list
10 Index (value, start index, end index) The first subscript position of an element, or a custom range
11 reverse() In situ flip
12 Sort (key=None, reverse=False) Quicksort, default sort from smallest to largest, key: algorithm
13 len() Gets the length of the list (element)

Case: judge this number on top of the list,2,2,3,6,4,5,6,8,9,78,564,456 [1], and output the subscript.

l = [1.2.2.3.6.4.5.6.8.9.78.564.456]
n = l.index(6.0.9)
print(n)

The output is 4
Copy the code

4. A tuple

The serial number function instructions
1 The list (tuples) The ancestor is converted to a list
2 Tuple (list) The list is transformed into an ancestor
3 The function operation of a meta-ancestor is roughly the same as that of a list

Example: Modify a tuple

# take 3 numbers of tuples with subscripts between 1 and 4 and convert them to a list
t = (1.2.3.4.5)
print(t[1:4])
l = list(t)
print(l)
# Insert a 6 at 2 in the list
l[2] =6
print(l)
Convert the modified list to a tuple and print it
t=tuple(l)
print(t)
Copy the code
Run the following command:

(2.3.4)
[1.2.3.4.5]
[1.2.6.4.5]
(1.2.6.4.5)
Copy the code

5. The string

The serial number function instructions
1 capitalize() Change the first character of the string to uppercase, followed by lowercase
2 casefold() Lower case the entire string
3 encode() Encode STR –bytes (binary string)
4 decode() decoding
5 count(sub,start,stop) Returns the number of occurrences of the character (sub), star: start subscript, stop: end subscript
6 find(sub,start,stop) If sub is not found, return -1
7 index(sub,start,stop) Returns the index of the first occurrence of sub
8 upper() Uppercase the string
9 lower() Converts a string to lowercase
10 The format () To print a string in some format

Example: Output a string in three formats: format ()

Method 1: Use numbers as placeholders (subscripts)

"{0} hey hey".format("Python")
a=100
s = "{0} {1} {2} hey hey"
s2 = s.format(a,"JAVA"."C++")
print(s2)

# 100JAVAC++ heh heh
Copy the code

Method 2: use {} to occupy space

a=100
s = "{} {} {} hey hey"
s2 = s.format(a,"JAVA"."C++"."C# ")
print(s2)

# 100JAVAC++ heh heh
Copy the code

Method 3: Use letters as placeholders

s = {a} {b} {c} hey hey"
s2 = s.format(b="JAVA",a="C++",c="C# ")
print(s2)

C++JAVAC# heh heh
Copy the code

6. The dictionary

The serial number function instructions
1 clear() Empty dictionary
2 copy() Shallow copy
3 Fromkeys (iterable, value=None) Create a dictionary based on the elements in the iterable
4 get(key,[d]) Get the value corresponding to the key, key is the key, d is the prompt message
5 items() Encapsulate key-value pairs in dictionaries into tuples and put them into a collection of classes
6 pop(key,[d]) Delete a dictionary key-value pair by key, where key is the key and d is the prompt
7 values() Return the value in the dictionary (class collection object)

Example: Looking up data in a dictionary

d = {"name": "Black"}
print(d.get("name2"."No trace."))
print(d.get("name"))
Copy the code
Run the following command:No trace of HeiCopy the code

Function of 7.

Functions are more of a custom function, there are not many commonly used built-in functions, there are mainly the following:

The serial number function instructions
1 The function name.doc Gets the document content of the function
2 Help (function name) View function documentation
3 Global variables Declare variables as global variables (can be used anywhere)
4 Nonlocal variable Declared variables are global variables (used for function nesting, where variables exist in the upper level of the function)

Example: Define a local variable in a function that can still be called after exiting the function

def fun1() :
    global b
    b=100
    print(b)
fun1()
print(b)
Copy the code
Run the following command:
100
100
Copy the code

8. Processes and threads

The serial number function instructions
1 os.getpid() Gets the number of the current process
2 multiprocessing.current_process() Gets the name of the current process
3 os.getppid() Gets the number of the current parent process
4 Thread(target=None,name=None,args=(),kwargs=None) Target: indicates the executable target. Name: indicates the name of the Thread. Default: Thread-n
5 start() Start child thread
6 threading.current_thread() Gets the name of the current process

Example: Inherit the Thread class implementation

# Multithreaded creation
class MyThread(threading.Thread) :
    def __init__(self,name) :
        super().__init__()
        self.name = name
    def run(self) :
        # thread things to do
        for i in range(5) :print(self.name)
            time.sleep(0.2)
 # instantiate the child thread
t1 = MyThread("Cool")
t2 = MyThread("Dearest person.")

t1.start()
t2.start()
Copy the code

9. Modules and packages

The serial number function instructions
1 The import module name The import module
2 From module name import function 1, function 2… Import module-specific functions
3 From module name import * Import all functions of the module
4 Import Module name AS alias Module definition alias
5 From module name import Function AS alias Function definition alias
6 The import package name. Module name. Target Package import method 1
7 The import package name. Subpackage name Module name The target Package import mode 2
8 The import package name. Module name Package usage form 1
9 The import package name. Module name AS alias The use form of package 2
10 From the package name. Module name import function Use form of package 3
11 From package name import Module name The use form of package 4
12 From the package name. The module name import * Package usage form 5

Case: How packages are used 4

from my_package1 import my_module3
print(my_module3.a)
my_module3.fun4()
Copy the code

10. File operations

(1) Routine file operation

The serial number function instructions
1 open(name,mode) Opens a file and returns a file object

Name: file name, — write full (file path + file name + suffix)

Mode: the mode of opening a file. The default is R — read only
2 write(“xxx”) Writes to a file
3 read() Read the contents of a file
4 close() Close the file

General mode of file operation:

model describe
r Opens a file as read-only with a pointer at the beginning
r+ Read/write, file pointer at the beginning
rb Read-only file pointer in binary form at the beginning
w Write only, file does not exist, create a new, exists, overwrite, pointer at the beginning
w+ Read/write, file does not exist, create a new, exists, overwrite, pointer at the beginning
wb Just write it, in binary form
a Append mode, file pointer at end
a+ Read and write, create if not exist, directly append exists
ab Append in binary form

The object property of file

The serial number methods instructions
1 closed Returns True if the file object is closed, False otherwise
2 mode Returns the access mode of the file object
3 name Returns the name of the file

File object method

The serial number function methods
1 close() Close the file
2 read([count]) Read the contents of the file, count: number of bytes
3 readlines() Read everything and pack it into a list
4 readline() Read a line of data, append it, and read too late to read again
5 Seek (offset, [from]) Change pointer position: move offset from from position

From: 0- start from the start position, 1- start from the current position, 2- start from the end

Soofset: Number of bytes to move
6 write() Writes to a file

(2) OS module

  • About the function of files

    The serial number methods instructions
    1 Os.rename (old file name, new file name) File renaming
    2 Os.remove (file name) Delete the file
  • About the function of folders

    The serial number function instructions
    1 Mkdir (folder name) Creating a folder
    2 Rmdir (folder name) Delete folders
    3 getcwd() Get the current directory
    4 Chdir (directory) Switch directory
    5 listdir() Gets all files or folders under the current folder, returning a list

    Listdir (‘ aa ‘) # get all files or folders under aa file, return a list

11. Modifier/decorator

The serial number function instructions
1 property To change a method to a property, the name of the modified method must be the same as the name of the method below the property
2 staticmethod Static method that removes the modified method from the class. This function does not access the attributes of the class
3 classmethod The difference with instance methods is that the first argument received is not self, but CLS (the concrete type of the current class)

The modified method does not have access to instance properties, but it does have access to class properties

Example: Examples of the use of classmethod

class B:
    age = 10
    def __init__(self,name) :
        self.name = name
    @classmethod
    def eat(cls) : # Ordinary function
        print(cls.age)

    def sleep(self) :
        print(self)

b = B("Little bitch.")
b.eat()

# run result :10
Copy the code

12. Regular

The serial number function instructions
1 Re.compile (regular expression) Compile the regular
2 match() Determines if the re is at the beginning of the string (matches the beginning of the line)
3 search() Scan the string to find the location that the RE matches (just the first one found)
4 findall() Find all the strings that re matches and return a list
5 group() Returns the string matched by re
6 start() Returns the position where the match began
7 end() Returns the position where the match ends
8 span() Returns the position of a tuple :(start, end)
9 findall() Returns all matched strings based on the regular expression
10 Sub (Re, new string, original string) Substitution string
11 Subn (Re, new string, original string) Replaces the string and returns the number of substitutions
12 split() Split string

Example: Use the split() function to split a string and convert it to a list

import re
s = "abcabcacc"
l = re.split("b",s)
print(l)

['a', 'ca', 'cacc']
Copy the code

Article I have all the function of them into the picture, there are 6 pieces, I needed can private chat, I will not be repeated here here, to increase the length of the article, the content is the same, you also can arrange their own function notes, in there are lots of things we don’t have a network or favorites, as long as have mobile phones, So we can look it up without barriers, very convenient.


conclusion

The purpose of this article, it is not to teach you how to use the function, but in order to quickly and easily to remember the commonly used function name, so there is no give you use every function, for example, you only remember the function name and its role, you will have a clue, as to the usage of function, baidu once, use a few times you will.

If you don’t even know the name of the function and its purpose, you will spend more time and energy than we can with purpose to look up the data faster.

Couldn’t help but think of the 2010-07 Python became the most popular language, annual oneself to start learning Python (before my master is a Java), function alone down dozens of pages of the book, commuters are carrying, out quickly for a time, whenever you have later once drank the wine, eat food taken late at night after work and colleagues from the ground when it comes to heaven, The bag was gone, the book was lost, the next day I regret… I have to write a new one.

To tell you the truth, Python is fun, and not so cold.