(1) Basic grammar
1.1. Notes
Add comments to the program, which can be used to explain the role and function of some parts of the program and improve the readability of the program. There are two forms of comments:
- Single-line comments: #
- Multi-line comments: single quotes ('''comment content''') or double quotes ("""comment content""")
1.2. Variables
Python is a weakly typed language. Variables can be assigned directly without declaration, and their data types can be changed dynamically.
1.3. Basic data types
- Numbers: integers (octal, decimal, hexadecimal), floating point, complex
- string
- Boolean type
Data type conversion:
1.4. Input and output
- input(): input
- print(): output
(2) Operators and expressions
2.1. Operators
arithmetic operator
assignment operator
comparison operator
Logical Operators
bitwise operator
- Bitwise AND (&): The binary representation of two operation data, only when the corresponding bit is 1, the result bit is 1, otherwise it is 0
- Bitwise or (|): The binary representation of two operation data, only the corresponding bit is 0, the result bit is 0, otherwise it is 1
- Bitwise exclusive OR (^); the result is 0 when the binary representations of the two operands are the same (both 0 or both 1), else 1
- Bitwise inversion (~): 1 in the corresponding binary is changed to 0, and 0 is changed to 1
- Left shift (<<): The binary operand is shifted to the left by the specified number of bits
- Right Shift (>>): Shift the binary operand to the right by the specified number of bits
2.2. Operator precedence
2.3, conditional expression
r = a if a > b else b
Equivalent to
if a>b:
r=a
else:
r=b
(3) Process control statement
3.1. Sequence structure
if
Single branch:
if 布尔表达式 1: 分支1
double branch
if 布尔表达1: 分支1 else: 分支2
multi-branch
if 布尔表达1: 分支1 elif 布尔表达2: 分支2 ..... else: 分支n
3.2. Loop structure
while
while 条件表达式: 循环体
while 条件表达式: 循环体 else: 语句块
for
for 变量 in 迭代对象: 循环体
for 变量 in 迭代对象: 循环体 else: 语句块
3.3、break、continue、pass
- break: to stop executing the deepest loop and start executing the next line of code
- continue: jump out of this loop
- pass: Empty statement, the function is to maintain the integrity of the program structure
(4) Sequence
4.1. List
1. Create:
Create directly: list name=[];
list() function creation: list name=list();
2. Add elements:
- Connector "+": used for connection between two lists
- a.append(b): Insert element b after list a (the inserted content is regarded as an element)
- a.extend(b): After inserting list b into list a, the inserted content is regarded as multiple
- a.insert(index,b): insert at the specified position, and insert the value b at the index position (starting from 0)
3. Modify:
Direct assignment: list name [index value] = new value
4. Delete:
del (): Specifies to delete the element.
pop(): delete the last element and return the value
remove(): removes the first occurrence of the specified element
5. Visit:
index(b, start, len): within the range from start to len, search for the first occurrence of the subscript of value b, start defaults to 0, and len defaults to the length of the list, that is, the entire list is searched by default
count(): Count the number of times Yuan Shu appears
6. Determine whether it exists : in (not in)
7. Slicing:
The format of the slice is: [start, end, step], the default step is 1
When there are only two parameters, it is [start, end], and it includes the left side and does not include the right side
The core of slicing is to quickly and flexibly select the elements of the list. After selection, a series of operations such as adding, deleting, modifying and checking can be performed.
Special operations for slices:
>>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[len(a):]=[10,11] // Add elements at the end >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> a[:3]=[] //Delete the first three elements >>> a [3, 4, 5, 6, 7, 8, 9, 10, 11]
8. Copy list:
- Shallow copy: direct assignment. For example: b=a[], the value of a is copied to b
- Deep copy: copy() or deepcopy() For example: b=copy.copy(a) or b=copy.deepcopy(a), copy the value in list a to b, copy is a class, you need to import
Shallow copy: After the value of a is copied to b, when the value of list a changes, the value of list b also changes
Deep copy: After a is copied to b, list a and list b are not impressed with each other
9. Sorting:
- Self-sorting method: sort(): descending order; reverse(): reverse order
- Built-in functions: sorted(): ascending order, reversed(): reverse order
- Shuffle the sort: shuffle() in random
10. Built-in functions :
- all: Whether all elements are equivalent to true (0 is flase, non-zero is true) that is: whether all elements are non-zero
- any: Whether all elements exist Elements are equivalent to true, that is: whether all elements have non-zero values
- max (list), min (list): find the maximum value of the list
- sum (list): the sum of all elements
- zip(list a, list b): Multiple lists are combined into tuples
- enumerate (list): returns the enumeration object
11. List comprehension:
list=[expression for var in range]
4.2, tuple
1. Create:
- Create directly: tuple name = (value 1, value 2.....)
- tuple (): tuple name = tuple (value 1, value 2.....)
- zip(a,b): a and b can be lists or tuples, connect a and b to generate tuples
2. Sequence unpacking:
Assign values to multiple variables at the same time
4.3. Dictionary
1. Create
create directly
dict()
dict.fromkeys(): only create values, no values
2. Read:
key as subscript: by key, read value
get method: read the value by key
items(): Returns a collection of key-value pairs, which requires traversal access
keys(): returns a collection of keys
values(): Returns a collection of values
3. Add and modify:
Dictionary name[key a]=value b: When key a does not exist, the statement is to add a key-value pair, and when key a exists, the value will be modified
4.4. Collection
create:
- create directly
- set() method: if the content is repeated, it will be automatically classified
delete:
- pop(): No parameters, delete the first element, return the deleted value
- remove(): Specifies to delete the element
- clear(): delete all elements
Increase : add(value)
operation
- Union: aIb
- Intersection: a&b
- Difference: ab
- Symmetric difference: a^b
- Judgment subset: a<b
(5) String
5.1, format string
Format:
'%[-][+][0][m][.n] formatting character'%exp[-]: Optional parameter, right aligned
[+]: optional parameter, left-aligned
[0]: optional parameter, means right alignment, fill in the blank space
[m]: Optional parameter, indicating the width
[.n]: optional parameter, indicating the number of digits reserved after the decimal point
Formatting characters: used to specify the type
exp: the item to transform
Commonly used formatting characters are:
2. The format method of the string object
{[index][:[[fill]align][sign][#][width][.precision][type]]}.format(args)args: used to specify the items to be converted, if there are multiple items, separated by commas
index: An optional parameter, used to specify the index position of the object to be formatted in the parameter list, and the index value starts from 0.
align: optional parameter, used to specify the alignment
The value is "<": indicates that the content is left-aligned;
The value is ">": indicates that the content is right-aligned;
A value of "=" indicates that the content is right-aligned,
Put the symbol on the leftmost side of the padding content, and it is only valid for numeric types;
A value of "^" indicates that the content is centered
sign: optional parameter, used to specify unsigned number
#: Optional parameter, for binary, octal and hexadecimal, if "#" is added, it means that the prefix 0b/0o/0x will be displayed
width: optional parameter, used to specify the occupied width.
.precision: optional parameter, used to specify the number of decimal places to keep
.precision: optional parameter, used to specify the number of decimal places to keep, the format is as follows:
5.2 Common methods
1. View help
- dir(""): View all methods of string manipulation
- help("".Method name): View the specific information of the method
2. String search
- The count() method is used to retrieve the number of occurrences of a specified string in another string
- find() method: Used to retrieve whether the specified substring is contained. Returns −1 if the retrieved string does not exist, otherwise returns the index of the first occurrence of the substring
- index() method: used to retrieve whether the specified substring is contained, and an exception will be thrown when the string does not exist
3. Separator
- split(), rsplit(): Split into multiple parts and return a list. If no delimiter is specified, a space character is used by default
- partiton(), rpartition(): split into three points, return a list, must specify the separator
4. Connection
- join: connect multiple characters, and specify the connection object, format: connector.join(connection object)
- +
5. Uppercase and lowercase conversion:
- lower(): Convert all uppercase letters to lowercase letters
- upper(): Convert all lowercase letters to uppercase
- capitalize(): Capitalize the first letter (the first word of the entire sentence)
- title(): capitalize each word
- swapcase(): uppercase becomes lowercase, lowercase becomes uppercase
6. Replacement
- replace(a, b): replace content a with content b
- translate(''.maketrans(a,b)): Replace a with b, which is a pair of replacements, for example
>>> a '123dsf' >>> a.translate(''.maketrans('0123','零一二三')) '一二三dsf'
7. Delete
- strip(): delete blank characters or specified characters on both sides
- rstrip(): delete the right blank character or the specified character
- lstrip(): delete left blank characters or specified characters
8. Evaluation
eval(): means to solve the formula
9. Determine the beginning or end character
- startswith() method: to retrieve whether the string starts with the specified substring. Return True if yes, False otherwise
- endswith() method: Used to retrieve whether the string ends with the specified substring. Return True if yes, False otherwise
10. Determine the string type
- isalnum(): Determine whether it is a letter or a number
- isalpha(): Determine whether it is an English letter
- isdigit(): Determine whether it is a number
- issupper(): Determine whether it is an uppercase letter
- islower(): Determine whether it is lowercase
- isspace(): Determine whether it is a blank character
11. Alignment
- center(): Center alignment, format: center (length, fill character)
- ljust(): left alignment
- rjust(): right alignment
5.3, coding
1. Encoding: encode():
str.encode([encoding="utf-8"][,errors="strict"])
- str: Indicates the string to be converted
- encoding="utf-8": optional parameter, used to specify the character encoding used when transcoding, the default is UTF-8, Chinese is gb2312
- errors="strict": optional parameter, used to specify the error handling method
2. Decoding:
bytes.decode([encoding="utf-8"][,errors="strict"])