[Quick Review of Python Language]——Basic Syntax

Table of contents

introduce

1. PEP8 code specifications and style

2. Variables and data

1. Variables

2. Operator

3. Three program structures

1. Branch structure

2. Loop structure

4. Combined data types

1. List

2. Tuple

3. Dictionary (dict)

5. Set

5. Strings and regular expressions

1. String basics

2. Advanced string methods

3. Regular expressions


introduce

 Python syntax query:https://www.runoob.com/python/python-dictionary.html

>>> country=2
>>> print("china",country)
china 2
>>> print(country,end='')
2
>>> country[]={1,2,3,4,5}
SyntaxError: invalid syntax
>>> country[]=[1,2,3,4,5]
SyntaxError: invalid syntax
>>> country=[1,2,3,4,5]
>>> print("country",country)
country [1, 2, 3, 4, 5]
>>> object=input("请输入年龄:")
请输入年龄:21
>>> print(type(age))
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print(type(age))
NameError: name 'age' is not defined
>>> print(type(object))
<class 'str'>
>>> object=int(input("请输入年龄:"))
请输入年龄:21
>>> print(type(object))
<class 'int'>
>>> #函数打印完后会自动换行,若不需要后加,end=‘’
>>> #有双引号或单引号的就当作字符串打印,没有则当作变量打印其内容(数值、字符、布尔、列表、字典等数据类型)

1. PEP8 code specifications and style

1. Global variablesUse English capital letters and use underscores between words_

SCHOOL_NANE="BUCT"

Global variables are generally only valid within the module. Implementation method: use the _ALL_ mechanism or add a leading underscore
2. Private variables Use English lowercase and one leading underscore
_student_name
3. Built-in variablesUse English lowercase, two leading underscores and two Post underscore
__maker__
4. General variablesUse English lowercase, and use underscores between words
class_name

Note: The first variable cannot use numbers, python keywords or reserved characters
pyrthon keyword 

>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> keyword.iskeyword('pass')
True

5. The function name is in English lowercase, with underlines between words to improve readability; do not use keywords, abbreviations, etc.
The first parameter of the instance method is always self
The first parameter of the class method is always cls

6. Attributes and classes
The naming of classes follows the rules of capital letters
The attributes (methods and variables) of classes are named in all lowercase letters and can be used Underline

7. Modules and packages
Use short lowercase English for module naming, and underscores can be used
Use short lowercase English for package naming. However, the use of underscores is not recommended

8. Regulations
A space must be used before and after the following operators:

= + - < > == >= <= and or not

Do not use spaces before or after the following operators:
 

*  /  **

2. Variables and data

Python is an object-oriented programming language, and everything in Python is an object. An object is one of the specific instances of a certain type. Each object has an identity, type, and value.

>>身份:身份(Identity)与对象是唯一对应关系,每一个对象的身份产生后就独一无二,无法改变。对象的ID是对象在内存中获取的一段地址的标识。
>>类型:类型(Type)是决定对象以那种数据类型进行存储的。
>>值:值(Value)存储对象的数据,某些情况下可以修改值,某些对象声明值过后就不可修改。

1. Variables

Variable: The name of the value pointing to the object, an identifier, and the name of the storage location in memory. Variables in python can be directly assigned without declaration. Since python uses dynamic type, the data type of the variable can be determined based on the assignment type.
Data type: dynamic type that can freely change the variable data type & static type that the variable is specified in advance, dynamic type is more flexible.

①Numbers(数字类型):int、float、complex
不可改变的数据类型,如果改变就会分配一个新的对象。整型、浮点型、复数
②Strings(字符串类型):str
序列类型
③Lists(列表类型):list
序列类型
④Tuples(元组类型):tuple
序列类型
⑤Dictionaries(字典类型):dict
映射类型
⑥Sets(集合类型):set
集合类型

The following is a brief introduction to integers, floating point types, complex numbers, Boolean types, and string types:
(1) Integer types: int, including positive integers and negative integers, is a long integer in python, with unlimited range (as long as the memory is large enough). In addition to decimal, binary 0b, octal 0o, and hexadecimal 0x also use integers, and the bases between them can be converted:

>>> a=15          
>>> print(bin(a))          
0b1111
>>> print(oct(a))          
0o17
>>> print(hex(a))          
0xf
>>> s='010011101'          
>>> print(int(s,2))          
157


Note: int(s,base) means converting the string s into decimal according to the base provided by the base parameter. The input of the built-in function input() is a string, which needs to be converted to an integer using the int() function.

(2) Floating point type: float, a value containing decimals, represents a real number, consisting of positive and negative signs, numbers and decimal points
fromhex (s): Convert hexadecimal floating point number to decimal number
hex(): Return hexadecimal floating point number in string form
is_integer( ): Determine whether it is a decimal. If the decimal is not 0, it returns False, if it is 0, it returns True

(3) Complex number type: complex consists of real numbers and imaginary numbers, with j or J added to the imaginary part (generally not available in other languages)

(4) Boolean type: bool is a subclass of the integer type, using the values ​​1 and 0 to represent the constants True and False. In Python, False can be a value of 0, an object of None, an empty string in a sequence, an empty list, an empty tuple, etc.

(5) string type: str, the character using one pair of single quotes, double quotes and three pairs of single quotes or double quotes It is a string, such as 'hello', "hello", etc. Obviously, the string is regarded as the value of the object, but strictly speaking, the string represents a type of object.

Extension: Call the type (variable name) function to view the type of the variable; call the help (function name) function to view the function usage

2. Operator

Arithmetic operators and logical operators are omitted here for the time being. You can check them by yourself when using them.


3. Three program structures

Sequential structure, branch structure, loop structure

1. Branch structure

①One-way condition
if expression:
    Statement block

②Bidirectional condition
if expression 1:
    Statement block 1
else expression 2: a>
    Statement block 2

③Multi-directional condition
if expression 1:
    Statement block 1
elif expression 2: < /span>     Statement block n< /span> else expression n: ...
    Statement block 2


Conditional nesting (be sure to control indentation) can express more complex logic

2. Loop structure

①for loop
for variable in sequence/iteration object:
    Loop body (statement block 1)
else :
    Statement block 2
Note: else will only be executed when the loop ends. If you use break to jump out, the else part will not be executed. Else can be omitted as needed . Range (start number, end number + 1, step size) can be used to generate a sequence of numbers. If the start is not specified, it starts from 0 by default, and the default step size is 1.
Example 1: Summing 1~100

>>> sum=0
>>> for s in range(1,101):
    sum = sum+s    
>>> print(sum)
5050

Example 2: Delete all even numbers between 1 and 10

>>> x=list(range(11))
>>> for i in x:
    x.remove(i)
else:
    print("奇数")
>>> print(x)
    
奇数
[1, 3, 5, 7, 9]

②For loop nesting
Example 1: Print multiplication table

>>> for i in range(1,10):
    for j in range(1,i+1):
        print(str(j)+'x'+str(i)+'='+str(j*i),end=' ')#转换为字符类型才能进行语句拼接,end使不换行
    print('')#换行

    
1x1=1 
1x2=2 2x2=4 
1x3=3 2x3=6 3x3=9 
1x4=4 2x4=8 3x4=12 4x4=16 
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 

③while loop
Use it when you don’t know the number of loops but know the loop conditions (note that there is no do while in python)
while loop conditions: a>     Statement block 2 else:
    Loop body (statement block 1)

Note: break jumps out of the loop at the current level and executes the statement after the loop; continue means ending this loop and proceeding to the next loop.


4. Combined data types

List, tuple, dictionary, set

1. List

The sequence type is an ordered collection of arbitrary objects. The elements are accessed through "position" or "index". It has the characteristics of variable objects, variable length, heterogeneity, and arbitrary nesting. (index starts from 0)

①Create a list

sample_list1 = [0,1,2,3,4]
sample_list2 = ["A","B","C","D","D"]

Elements of different data types are allowed in lists:

sample_list3 = [0,"a",3,'python']

Lists can be nested:

sample_list4 = [sample_list1,sample_list2,sample_list3]

②Use list

sample_list1 = [0,1,2,3,4]
print(sample_list1[1])  #1
>>> print(sample_list1[-2])#从列表右侧倒数第2个元素:3

del sample_list1[2]#以索引方式删除元素
sample_list1.remove('2')#直接以值的方式删除元素

del sample_list1  #删除整个列表

sample_list1=[]   #清空列表

③Built-in functions & other methods in the list

>>> print(len(sample_list1))
5
>>> print(max(sample_list1))
4
>>> print(min(sample_list1))
0
>>> a = (0,1,2,3,4)
>>> print(list(a))  #将元组转换为列表
[0, 1, 2, 3, 4]

>>> sample_list1.append(5)   #末尾添加
>>> print(sample_list1)
[0, 1, 2, 3, 4, 5]
>>> b = [6,7,8,9]
>>> sample_list1.extend(b)   #扩展(序列合并)
>>> print(sample_list1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sample_list1.insert(0,3)  #在特定索引位置插入元素
>>> print(sample_list1)
[3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sample_list1.reverse()    #翻转元素顺序
>>> print(sample_list1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 3]
>>> print(sample_list1.count(3))   #计数元素出现次数
2
>>> print(sample_list1.index(8))   #获取元素所在索引(位置)
1

其他还有pop、remove、sort、copy、clear等

2. Tuple

is a sequence type like a list. It is also an ordered collection of arbitrary objects. Its elements are also accessed through index (position). It also has the characteristics of variable length, heterogeneity and arbitrary nesting. Unlike lists, the elements in tuples are unmodifiable.
①Create tuple

sample_tuple1 = (0,1,2,3,4)
sample_tuple2 = ("p",'python',1989)

Elements can be of various iterable types, or they can be empty:

sample_tuple3 = ()

If there is only one element, add a comma after the element to avoid ambiguity, otherwise the parentheses will be treated as operators:

sample_tuple4 = (123,)

Tuples can also be nested:

sample_tuple5 = (sample_tuple1,sample_tuple2)

②Using tuples
also uses index access (also square brackets []):

>>> tuple = (1,2,3,4,5,6)
>>> print(tuple[2])
3
>>> print(tuple[-3])
4

Supports slicing operations:

>>> print(tuple[:])    #全部元素
(1, 2, 3, 4, 5, 6)
>>> print(tuple[2:4])  #索引为2和3的元素,不包括索引为4的
(3, 4)
>>> print(tuple[2:])
(3, 4, 5, 6)
>>> print(tuple[0:5:2])
(1, 3, 5)

Delete a tuple:

del tuple

③Built-in functions of tuples

len, max, min, tuple, etc., similar to lists, tuple(listname) converts the list into a tuple

3. Dictionary (dict)

Dictionary is a mapping type, which implements access to elements through keys. It has the characteristics of unordered, variable length, heterogeneous, nested, and variable type containers.
①Create dictionary

dict1 = {'Name':'Xiaohuang','City':'Beijing','School':'BUCT'}
dict2 = {12:34,56:78,45:67}
dict3 = {'Name':'Xiaohuang',12:34,'School':'BUCT'}

If a key is assigned twice, the first value is invalid:

dict4 = {'Name':'Xiaohuang','City':'Beijing','School':'BUCT','City':'Henan'}

Nesting is also supported:

dict5 = {'student':{'stu1':'Xiaoming','stu2':'Xiaohong','stu3':'Xiaogang'},
'school':{'sch1':'Tsinghua','sch2':'Penking','sch3':'BUCT'}}

②Use dictionary
Use key access, also with square brackets []:

>>> print(dict1['City'])
Beijing
>>> print(dict2[56])
78
>>> print(dict5['student'])
{'stu1': 'Xiaoming', 'stu2': 'Xiaohong', 'stu3': 'Xiaogang'}
>>> print(dict5['student']['stu2'])   #嵌套访问
Xiaohong

Modify existing values:

>>> dict1['City'] = 'Henan'
>>> print(dict1['City'])
Henan

Add new key-value elements to the dictionary:

>>> dict1['Age'] = 21
>>> print(dict1)
{'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT', 'Age': 21}

Delete an element and the entire dictionary:

>>> del dict1['School']
>>> print(dict1)
{'Name': 'Xiaohuang', 'City': 'Henan', 'Age': 21}
>>> del dict1
>>> print(dict1)
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    print(dict1)
NameError: name 'dict1' is not defined

③Dictionary built-in functions and methods
len, str output dictionary, type:

>>> len(dict2)
3
>>> str(dict2)
'{12: 34, 56: 78, 45: 67}'
>>> type(dict2)
<class 'dict'>

Other built-in methods:
①dictname.fromkeys(sequence, value)

>>> seq1 = ('Name','City','School')
>>> seq2 = ['Name','City','School']
>>> dict1 = {}
>>> dict1 = dict1.fromkeys(seq1)
>>> print(dict1)
{'Name': None, 'City': None, 'School': None}
>>> dict2 = {}
>>> dict2 = dict2.fromkeys(seq2,10)
>>> print(dict2)
{'Name': 10, 'City': 10, 'School': 10}

②key in dictname, if it is, return True otherwise False

>>> 'Name' in dict2
True

③dictname.get(key)

>>>dict2 = {'Name': 10, 'City': 10, 'School': 10}
>>> print(dict2.get('Name'))
10
>>> print(dict2.get('Age'))
None
>>>dict5 = {'student':{'stu1':'Xiaoming','stu2':'Xiaohong','stu3':'Xiaogang'},'school':{'sch1':'Tsinghua','sch2':'Penking','sch3':'BUCT'}}
>>> print(dict5.get('student').get('stu1'))  #嵌套使用
Xiaoming

Comparison:
The dictname.get(key) method can return the default value None or the set default value when the key (key) is not in the dictionary.
dictname[key] will trigger a KeyError exception when key is not in the dictionary.

④dictname.keys()、dictname.values()、dictname.items()

>>> dict1 = {'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT', 'Age': 21}
>>> print(dict1.keys())
dict_keys(['Name', 'City', 'School', 'Age'])
>>> print(dict1.values())
dict_values(['Xiaohuang', 'Henan', 'BUCT', 21])
>>> print(dict1.items())  #返回可遍历的元组数组
dict_items([('Name', 'Xiaohuang'), ('City', 'Henan'), ('School', 'BUCT'), ('Age', 21)])
>>> for key,value in dict1.items():
    print(key,':',value)
    
Name : Xiaohuang
City : Henan
School : BUCT
Age : 21

④dictname.update(dictname1)

>>> dict1 = {'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT', 'Age': 21}
>>> dict2 = {}
>>> dict2.update(dict1)
>>> print(dict2)
{'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT', 'Age': 21}

⑤dictname.pop(key), delete the corresponding key value, and the return value is the value corresponding to the key

>>> dict1 = {'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT', 'Age': 21}
>>> x = dict1.pop('Name')
>>> print(x)
Xiaohuang
>>> print(dict1)
{'City': 'Henan', 'School': 'BUCT', 'Age': 21}

⑥dictname.popitem() pops up the last set of key values ​​(return value) and deletes it

>>> x = dict1.popitem()
>>> print(x)
('Age', 21)
>>> print(dict1)
{'Name': 'Xiaohuang', 'City': 'Henan', 'School': 'BUCT'}

5. Set

A collection is a collection type (unordered, non-repeatable), which represents a collection of arbitrary elements. Indexing can be performed through another collection of arbitrary key values, and can be arranged and hashed in an unordered manner.
Mutable collection set: After creation, it can be changed through various methods, such as add(), update(), etc.
Immutable collection frozenset: Hashable (An object's hash value will not change during its lifetime and can be compared with other objects). It can also be used as an element in other collections, or as a key in a dictionary.

①Create a set
It can be created using {}, or set() or frozenset(). In order to prevent ambiguity with the dictionary, you must use when creating an empty set:
empty = set() cannot be used empty = {}

>>> set1 = {1,2,3,4,5,6}
>>> set2 = {'a','b','c','d','e'}
>>> set3 = set([10,20,30,40,50])
>>> set4 = frozenset(['huang','zhang','zhao'])

②Use sets
The dictionary can remove duplicate elements by itself:

>>> set5 = {1,2,3,4,5,6,1,2,3}
>>> print(set5)
{1, 2, 3, 4, 5, 6}
>>> print(len(set5))
6

The collection is unordered and does not have an "index" or "key" to specify the element to be called, but it can be output in a loop:

>>> for x in set5:
    print(x,end=' ')
    
1 2 3 4 5 6 

To add elements, update does not allow integers and only allows sequences:

>>> set5.add(7)
>>> print(set5)
{1, 2, 3, 4, 5, 6, 7}
>>> set5.update('huang')
>>> print(set5)
{'g', 1, 2, 3, 4, 5, 6, 7, 'u', 'h', 'a', 'n'}
>>> set5.update('89')
>>> print(set5)
{'g', 1, 2, 3, 4, 5, 6, 7, 'u', '8', 'h', 'a', 'n', '9'}
>>> set5.update(1234)  #不允许int
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    set5.update(1234)
TypeError: 'int' object is not iterable

Member test:

>>> 'h' in set5
True
>>> 1 not in set5
False

Set operations:

>>> set1 = {1,2,3,4,5}
>>> set2 = {3,4,5,6,7}
>>> set1 - set2  #差集
{1, 2}
>>> set1 | set2  #并集
{1, 2, 3, 4, 5, 6, 7}
>>> set1 & set2  #交集
{3, 4, 5}
>>> set1 ^ set2  #对称差集
{1, 2, 6, 7}

Delete elements:

>>> set1.remove(3)
>>> print(set1)
{1, 2, 4, 5}

③There are many methods of collection
. . . Omitted, please refer to python language knowledge points for details: https://www.runoob.com/python/python-dictionary.html


5. Strings and regular expressions

String is used to represent text type data. It is also an ordered collection of character arrays. The sequence cannot be changed, and the index also starts from 0.
Regular expressions are special strings that operate on strings. Regular expressions can be used to verify whether the corresponding string complies with the corresponding rules.

1. String basics

The characters of the string can be ASCII characters, or other various symbols, accompanied by single quotes, double quotes, and triple quotes.
Some special characters are called escape characters, which are used when direct input is not possible:

\\(反斜线)、\'(单引号)、\"(双引号)、\a(响铃符)、\b(退格)、\f(换页)、
\n(换行)、\r(回车)、\t(水平制表符)、\v(垂直制表符)、\0(Null空字符串)、
\000(以八进制表示的ASCII码对应符)、\xhh(以十六进制表示的ASCII码对应符)

①Basic string operations
Find the length of the string:

>>> str1 = 'I love python'
>>> print(len(str1))
13

String concatenation:

>>> str2 = 'I','love','python'
>>> print(str2,type(str2))
('I', 'love', 'python') <class 'tuple'>
>>> str3 = 'I''love''python'
>>> print(str3,type(str3))
Ilovepython <class 'str'>
>>> str4 = 'I'+'love'+'python'
>>> print(str4,type(str4))
Ilovepython <class 'str'>
>>> str5 = 'love'*5
>>> print(str5)
lovelovelovelovelove

String traversal:

>>> str6 = 'Python'
>>> for s in str6:
    print(s)

Contains judgment:

>>> print('P' in str6)
True
>>> print('y' not in str6)
False

Can be retrieved by index but cannot be modified:

>>> print('P' in str6)
True
>>> print('y' not in str6)
False
>>> print(str6[2])
t
>>> print(str6[:3])
Pyt
>>> print(str6[3:])
hon
>>> str6[0] = 'p'   #报错不可修改
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    str6[0] = 'p'
TypeError: 'str' object does not support item assignment

②String formatting
Use the format() method:

>>> print(' I am {0},and I am from {1}'.format('Liming','China'))
 I am Liming,and I am from China

Use formatting symbols:
%s, %r, %c, %b, %o, %d, %i, %f, etc. (see details on your own)

% can be understood as a placeholder, followed by the actual parameters to be followed. The essence of the actual parameters is a tuple.

>>>print(' I am %s,and I am from %s'%('Liming','China'))
 I am Liming,and I am from China
>>> print('花了%.2f元'%(19.56789))
花了19.57元

2. Advanced string methods

①strip deletes the first and last characters. If no characters are specified, the first and last spaces or newlines are deleted by default

>>> str1 = ' Hello world*##'
>>> print(str1.strip())   
Hello world*##
>>> print(str1.strip('#'))
 Hello world*
>>> print(str1.strip('*##'))
 Hello world

②count counts the number of times a certain character appears within the specified range

>>> str2 = '101010101010'
>>> print(str2.count('1',2,10))  #不包括索引为10的末尾
4

③capitalize capitalizes the first letter of the string

>>> str3 = 'xiaohuang'
>>> print(str3.capitalize())
Xiaohuang

④replace replacement characters, if the third parameter is not specified, all substitutions will be replaced by default

>>> str2 = '101010101010'
>>> print(str2.replace('10','89'))
898989898989
>>> print(str2.replace('10','89',2))
898910101010

⑤find searches for characters within the specified range and returns the index number (returns -1 if not found, returns the index number of the first occurrence if it appears multiple times)

>>> str4 = '01234507'
>>> print(str4.find('2'))
2
>>> print(str4.find('2',3,8))
-1
>>> print(str4.find('0'))
0

⑥index is the same as find but an error will be reported if not found

>>> print(str4.index('8'))
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    print(str4.index('8'))
ValueError: substring not found

⑦isalnum determines whether the string consists entirely of letters or numbers

>>> str5 = 'aaaa1111'
>>> str6 = 'asdfgg'
>>> str7 = 'ash17%%#'
>>> print(str5.isalnum(),str6.isalnum(),str7.isalnum())
True True False

Similar functions include:

isalpha determines whether it is composed entirely of letters
isdigital determines whether it is composed entirely of numbers
isspace determines whether it is composed entirely of spaces
islower determines whether it is all lowercase
isupper determines whether it is all uppercase
istitle determines whether the first letter is uppercase
⑧lower , upper, all changed to lowercase or uppercase

>>> str8 = 'aBcDeF'
>>> print(str8.lower())
abcdef
>>> print(str8.upper())
ABCDEF

⑨split (sep, maxsplit) splits according to the specified sep characters (if sep is not specified, the default is to split spaces), maxsplit is the number of splits (if no sep is specified, the default is to split all)

>>> str9 = 'uhaduadhaxbu'
>>> print(str9.split('a'))
['uh', 'du', 'dh', 'xbu']
>>> print(str9.split('a',2))
['uh', 'du', 'dhaxbu']
>>> str10 = 'I love python'
>>> print(str10.split())
['I', 'love', 'python']

⑩startswith determines whether (within the specified range) starts with the specified character; endswith determines whether (within the specified range) ends with the specified character

>>> str11 = '13hhhh'
>>> print(str11.startswith('13'))
True
>>> print(str11.startswith('13',2,5))
False
>>> print(str11.endswith('hh',2,6))
True

⑩partition (sep), divided into three parts based on the first occurrence of sep., returns a triplet, if there is no sep, returns a space; repartition (sep), with The last occurrence of sep is divided into three parts

>>> str12 = '1234561234'
>>> print(str12.partition('34'))
('12', '34', '561234')
>>> print(str12.partition('78'))
('1234561234', '', '')
>>> print(str12.rpartition('12'))
('123456', '12', '34')

3. Regular expressions

Regular expression, that is, an expression that describes a certain rule, code abbreviation regex, regexp or RE. It uses some single strings to describe or match strings of a certain syntax rule. In many text editors, RE is used to retrieve or replace text that matches a certain pattern:
Form – P84? ? ? ? ? ? ? ? ? ? ? ? ? Don't you know what to do? ? ?

①re module
The re module provides the methods required for regular expression operations

>>> import re
>>> result = re.match('huang','huang666')  #匹配
>>> print(result.group())  #group用于只返回匹配结果
huang
>>> print(result)
<_sre.SRE_Match object; span=(0, 5), match='huang'>
#match与search的区别,search就算不是从开头对应也能匹配到
>>> result1 = re.match('huang','xiaohuang')  #匹配不到huang
>>> print(result1.group())
AttributeError: 'NoneType' object has no attribute 'group'
>>> result2 = re.search('huang','xiaohuang') #匹配到huang
>>> print(result2.group())
huang

Guess you like

Origin blog.csdn.net/weixin_51658186/article/details/133976354