程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics

編輯:Python

cover Python Basic grammar , Master basic programming skills


Python Basic grammar

know Python

Python It's a kind of object-oriented Of Interpretive computer programming language , By Guido . Van Rossum developed , The first public release was released on 1991 year , It is often called Glue language , Be able to make various modules in other languages ( In especial C/C++), Constant easy connection .

  1. Python advantage

    1. Easy to learn
    2. Free and open source

      Python Open source , Developers are free to download , read , Even modify Python Source code

    3. Rich third-party library

      Python It has its own rich and Powerful library , And because of Python Of Open source , There are also many third-party libraries , for example : stay web Development has django.flask,Tornado, Reptiles scrapy, Scientific Computing numpy.pandas wait

    4. It can be transplanted

      because Python It's open source. , It has been ported to most platforms , for example :Windows,MacOS,Linux,Andorid,iOS wait

    5. object-oriented

      Python Both Support process oriented , It also supports object-oriented , This makes programming more flexible

  2. Python shortcoming

    1. Slow running speed

      C The program is very slow , because Python It's interpreted language , The code is translated line by line into CPU Machine code that can be understood , This translation process is very time-consuming , So it's slow , and C The program is compiled directly into CPU Executable machine code , therefore relative Python for ,C The language executes very fast

    2. Code cannot be encrypted

      To publish the program you wrote , In fact, the source code is released , It is Interpretive language , The source code must be released

    3. Forced indentation

      Python There are very Strict indentation Syntax , As long as the indentation error, the program crashes immediately

    4. GIL Global interpreter lock

      At any moment , Only one thread runs in the interpreter , Yes Python Access to the virtual machine is locked by the global interpreter (GIL) To control , Formally, this lock can ensure that only one thread is running at the same time , encounter i/o When blocked, it will release (GIL) therefore Python Multithreading is not really multithreading , It is CPU Very fast execution , It doesn't make people feel GIL The existence of .(GIL) Will be in Python Advanced stage explanation

    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-2eiqPEK6-1657892353562)(1.png)]

     To learn the Python Can do
    

master Python notes

Comments are when you write a program , The person who wrote the program gave a sentence 、 Procedures section 、 Functions, etc Explain or prompt
The function of annotation :
A comment can serve as a comment , This method function , What on earth is a variable , If there is no comment for a long time, even if you write your own code , Maybe I don't know what this code is for , Therefore, the function of comments is to facilitate you to view the written code , Others to receive your code can understand , Simply put, it will be to improve the readability of the program code , For future reference 、 modify
Python in Use... For single line comments # Number ,# To the right of the number is the content of the note ,Python The parser encountered # The number will be used as a comment , Will not parse # After the number
Multiline comment ‘’‘ Code … ‘’’


master Python Definition and naming rules of variables

  • Variable = Stored data
  • A variable is a contiguous storage space with a name , We can apply for and name such storage space by defining variables , And use this storage space by the name of the variable
  • Variables are places where data is stored temporarily in a program
    Python It's a kind of Strong language , There is no need to specify the data type when assigning variables , What data type is assigned to this variable , What kind of variable is this
#x It's a variable , When x=2 The result is 6 x=10 The result is 30
x=2
y=x*3
print(y)

Naming rules
Variables must be in letters (a-z A-Z) Underline (_) start , Other characters can be alphanumeric underscores , Variables are case sensitive ,Python Keywords cannot be used as variable names

_Name=' Zhang San '
name=' Lau Andy '
print(_Name,name)

Naming specification

  • Jane knows what she means , Try to use semantic words to name , If you use Password Use as password ,username Use as user name
  • Little hump nomenclature : The first word is lowercase, and the other words are capitalized, such as userName
  • Big hump nomenclature : All words are capitalized , Such as UserName
  • Underline nomenclature : Use... For each word _ Underline connection , Such as user_name

master Python Basic operators

  • Arithmetic operator :+ - * / **( Index ) %( Remainder ) //( Divide and round )

Set two variables a=7,y=3

Arithmetic operator Function description Example + Add Arithmetic addition a+b=10- Subtraction Arithmetic subtraction a-b=4* Multiplication Arithmetic multiplication x*y=21** Index The number on the left is the base , The number on the right is the exponent a* *b=343% Remainder x%y x Divide y The remainder of a%b=1/ division x/y The result contains the number after the decimal point a/b=2.33333333335// Divide and round x//y The result is to ignore the decimal places after the decimal point , Keep only whole digits a//b=2
  • Comparison operator :==( be equal to ) !=( It's not equal to ) > < >= <=

Return to Boolean True False

Comparison operator name Example Description of results == be equal to x==y If x Exactly equal to y, It is true != It's not equal to x!= If x It just doesn't equal y It is true > Greater than x>y If x( Left parameter ) Greater than y( Parameters on the right ), It is true < Less than x< y If x( Left parameter ) Less than y( Parameters on the right ), It is true >= Greater than or equal to x>=y If x( Left parameter ) Greater than or equal to y( Parameters on the right ), It is true <+ Less than or equal to x<=y If x( Left parameter ) Less than or equal to y( Parameters on the right ), It is true
  • Logical operators and or not
Logical operators example Description of results andx and yx,y Both are true , The result is true , If one is false , The result is false orx or yx, y One is true , That's true , All false , The result is false notnot x Take the opposite , If x It's true , The result is false , If x For false , The result is true

a=1
b=2
c=3
d=5
print(a>b and d>c) # The result is false 
print(a>b or d>c)# The result is true 
print(not a>d) # The result is true 

priority :()–>not–>and–>or

print(2>1 and 1<4 or 2<3 and 9>6 or 2<4 and 3<2) #True
Assignment operator Function description Description of results = Assignment operator take = The value on the right of the sign is assigned to the variable on the left += Addition assignment operator c+=a Equivalent to c=c+a-= Subtraction assignment operator c-=a Equivalent to c=c-a*= Multiplication assignment operator c*=a Equivalent to c=c*a/= Division assignment operator c/=a Equivalent to c=c/a%= Modulo assignment operator c%=a Equivalent to c=c%a**= Power assignment operator c* =a Equivalent to c=c *a//= Rounding assignment operators c//=a Equivalent to c=c//a
a,b,c,d=23,10,18,3
a+=3
print(a)

master Python Input and output

Output % Place holder

  • Python There is a simple character formatting method , Use % Do a placeholder ,% Followed by the type of variable %s %d
  • At output time , If there is \n, here \n The next line will show Line break
name =' Zhang San '
classPro=' Peking University, '
age =22
print(' My name is %s: come from %s This year, %d Year old '%(name,classPro,age))
me =' my '
classP=' First grade of Tsinghua high school 3 class '
age1=7
print('%s The name is Xiao Ming , come from %s, I this year %d Year old '%(me,classP,age1))
print(' I can \n A new line ')
  • %c character
  • %s adopt str() String conversion to format
  • %d Signed decimal integers
  • %u An unsigned decimal integer
  • %f Floating point numbers
print('\n')
print('-------------test---------------')
print('\n')
ID=' The professor '
QQ=66666666
number=13467204515
address=' Baiyun District, Guangzhou '
print('========================================')
print(' full name :%s'%ID)
print('QQ: %d'%QQ)
print(' Phone number :%d'%number)
print(' The company address :%s'%address)
print('========================================')
print('\n')

Formatting output is another way


print('--------- Formatting output is another way .format------------')
print(' full name :{}'.format(ID))
print('QQ:{}'.format(QQ))
print(' Phone number :{}'.format(number))
print(' The company address :{}'.format(address))

Input input

Python Provided in the input Method to get keyboard input
input The keyboard input received is str type , If you receive a numeric type, you need to str Turn into int


name=input(' Please enter a name ')
age2=int(input(' Please enter age :'))
qq=input(' Please enter QQNumber:')
phone=input(' Please enter your mobile number :')
addr=input(' Please enter the address :')
print(' full name :%s Age is %d'%(name,age2))
print('QQ:{}'.format(qq))
print(' Phone number :{}'.format(phone))
print(' The company address :{}'.format(addr))

Python Process control

  • Python A conditional statement is the result of execution through one or more statements 【True/False】 To determine the code block to execute
  • Is the order in which the computer executes code
  • Process control : Effectively manage the execution sequence of computer code , Only process control can realize the business logic in development
  • Classification of process control :
    • Sequential process : Code is a top-down execution structure , It's also python The default process
    • Choose the process / Branch process : According to the judgment at a certain step , A structure that selectively executes the corresponding logic
      • Single branch if Conditional expression :
      • Double branch if Conditional expression : else:
      • Multiple branches if Conditional expression : elif Conditional expression : elif Conditional form : else:
      • Conditional expression : Comparison operator / Logical operators / Match operator
    • Circulation process : Under certain conditions , The logic of repeatedly executing a piece of code 【 Thing 】
      • while Conditional expression :
      • for Variable in Iteratable collection objects

Single branch

score = 80
if score<=60: # If the conditions are met, the print prompt will be output 
print(' The results are not ideal , Continue refueling ')
pass # Empty statement 
print(' End of statement ')

Double branch

if score>60:
print(' Good results. ')
else:
print(" The result is not up to standard , Continue to work hard ")

Multiple branches

  • features : As long as one of the branches is satisfied , Will exit this layer if Sentence structure 【 One of the branches must be executed 】
  • There are at least 2 There are two situations you can choose
  • elif Conditions and statements must be written later
  • else It's optional , Fill in according to the actual situation

grade=int(input(' Please enter the grade :'))
if grade>90:
print(' Your score is A etc. ')
pass
elif grade>=80:
print(' Your score is B etc. ')
pass
elif grade >=70:
print(' Your rating is C etc. ')
pass
elif grade >=60:
print(' Your rating is D etc. ')
pass
else:
print(' You bastard ')
print(' End of program running .........')

if-else nesting

  • A scene needs to be divided into stages or levels , Make a different deal
  • Executes if Statements must be external if Only when the statement satisfies the condition can ,
xuefen=int(input(' Please enter your credits '))
if xuefen >10:
grade = int(input(' Please enter your score '))
if grade>=80:
print(' You can be promoted ... Congratulations ')
pass
else:
print(' unfortunately , Your grades are not up to standard ....')
pass
pass
else:
print(' Your performance is too bad 0')

Cycle classification while for

while Grammatical structure

Grammatical features
# 1. There is an initial value
# 2. Conditional expression
# 3. Variable 【 Circulating body count variable 】 Self increasing and self decreasing , Otherwise, it will cause a dead cycle

  • Conditions of use : The number of cycles is uncertain , It ends with a loop condition
  • Purpose : In order to make similar or identical code operations more concise , Make the code reusable

for loop

  • Traversal operation , Take each value in the collection container in turn
tage=' I am a Chinese '# The string type itself is a collection of character types 
for item in tage:
print(item)
pass
#range This function can generate a list of data sets 
#range( Starting value : End value : step ) Step cannot be 0
sum=0
for data in range(1,101):# The data contains , The right side does not contain 1-100
sum+=data
pass
#print(data,end=' ')
print(sum)
print('sum=%d'%sum)
# print('sum={}'.format(sum))
#
for message in range(50,201):
if message%2==0:
print('%d It's even '%message)
pass
else:
print('{} Is odd '.format(message))
# break Represents the end of the interrupt , If the conditions are met, the cycle of this layer will be ended directly 
# continue End this cycle , Continue with the next cycle , ( When continue When conditions are met , The remaining statements in this loop will not be executed , The following cycle continues )
# These two keywords can only be used in a loop 

while: For unknown number of cycles 【 Used to judge 】
for : Suitable for a known number of cycles 【 Iteratable object traversal 】

99 The multiplication table is used for Realization

# multiplication table 
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%d'%(i,j,i*j),end=' ')
print()# Control line feed 
print('--------------------------------------------------------')
print('\n')

Case study Input 1-100 Data between

# Input 1-100 Data between 
index =1# Defining variables 
while index<=100:
print(index)
index+=1
pass

Case guessing game

# Case guessing game 
import random
count =1
while count<=10:
person =int(input(' Please punch :【0 stone 1 scissors 2 cloth 】\n'))
computer=random.randint(0,2)# Random number range 
if person==0 and computer==1:
print(' you are awesome ')
pass
elif person==1 and computer==2:
print(' You're great ')
pass
elif person==2 and computer==0:
print(' you are awesome ')
pass
elif person==computer:
print(' Good ah , Even tied ')
pass
else:
print(' Did you lose ')
pass
count+=1

multiplication table

# Print the multiplication table 
i=1
while i<=9:
j=1
while j<=i:
print('%d*%d=%2d'%(i,j,i*j),end=" ")
j+=1
pass
print()
i+=1
pass

right triangle

# right triangle 
row=9
while row>=1:
j=1
while j<=row:
print('*',end=' ')
j+=1
pass
print()
row-=1
pass

an isosceles triangle

# an isosceles triangle 
i=1
while i<=10:
j1=1
while j1<=10-i:# Control the number of blank spaces in printing 
print(' ',end='')
j1+=1
pass
k=1
while k<=2*i-1:# Control printing * Number 
print('*',end='')
k+=1
print()
i+=1
pass

Guess age games

There are three requirements :
1. Allow users to try up to 3 Time
2. Every attempt 3 Next time , If you haven't guessed right , Just ask the user if he still wants to play , If the answer is Y or y, Just keep guessing 3 Time , In this way , If the answer is N or n, Just quit the program
3. If you're right , immediate withdrawal


# # import random
#
# # for i in range(3):
# # computer = random.randint(20, 22)
# # person = int(input(' Please enter age :'))
# # if person == computer:
# # print(' Congratulations on your correct answer ')
# # break
# #
# # else:
# # print(' Wrong guess. ')
# # zimu=input(' Whether or not to continue : Please input if you want to continue Y perhaps y Please input N or n')
# # if zimu=='Y' or zimu =='y':
# # pass
# # elif zimu=='N' or zimu=='n':
# # exit()
time =0
count=3
while time<=3:
age =int(input(' Please enter the age you want to guess :'))
if age ==25:
print(' You're right :')
break
elif age >25:
print(' You guessed it ')# else:
print(' Guess it's small ')
time+=1
if time==3:
choose=input(' Do you want to continue ?Y/N')
if choose == 'Y' or choose=='y':
time=0# Reset to initial value 
elif choose=='N' or choose=='n':
exit()
else:
print(' Please enter the correct symbol .. Thank you for your cooperation ')

Xiao Wang's height 1.75, weight 80.5kg, Please according to BMI The formula ,【 Weight divided by the square of height 】, Help Xiao Wang calculate his BMI Index , And according to BMI Index

lower than 18.5 Over light
18.5-25 normal
25-28 overweight
28-32 obesity
higher than 32 Severe obesity
use if-elif Judge and print out


high=1.75
weight=80.5
BMI=weight/(high*high)
print('BMI The data of {}'.format(BMI))
if BMI<18.5:
print(' Over light ')
elif 18.5<=BMI<25:
print(' normal ')
elif 25<=BMI<28:
print(' overweight ')
elif 28<=BMI<32:
print(' obesity ')
else:
print(' Severe obesity ')
## Python data type 
> master Python Basic data types for
* Numbers
* int( Signed integers )
* long( long integer )(Python3 Version cancelled )
* float( floating-point )
* complex( The plural )
* bool( Boolean value )
* return True False
* character string
* Dictionaries
* Tuples
* list
```python
a=[]
print(type(a)) #type Method to view the type of the variable 
b=10
print(type(b))

Python data type

character string

  • Sequence : A set of values arranged in order ,【 Data set 】

  • Python in 3 The built-in sequence type in :
    ‘’’
    character string list Tuples
    ‘’’

  • Sequence advantages : Supports indexing and slicing operations

  • features : The first positive index is 0, It points to the left end , The first index is negative , It points to the right end

  • Slicing refers to intercepting a certain section of a string ,

  • Slicing uses Syntax :[ Start subscript : End subscript : step ] The content intercepted by the slice does not contain the data corresponding to the end subscript , Step size refers to getting a character every few subscripts

  • The subscript will cross the line , Slice won't :


Test='python'
print(type(Test))
print(Test[0])# Get the first character 
print(' Get the second character %s'%Test[1])
for i in Test:
print(i,end=' ')
name='peter'
print(' title case :%s'%name.capitalize())
a=' python '
print(a.strip())# Remove the spaces on both sides 
print(a.lstrip())# Remove the space on the left 
print(a.rstrip())# Remove the space on the right 
# Assignment string 
b=a
print(b)
print(id(a))# Check the memory address 
print(id(b))
str="I Love Python"
print(str.find('P'))# Return the corresponding subscript Find the corresponding position of the target object in the sequence No return found -1
print(str.index('v'))#index() Check if there is a substring in the string , Return the corresponding subscript , If you don't find it, report it wrong 
print(str.startswith('I'))# Return to Boolean Decide whether to start with something 
print(str.endswith('i'))# Judge whether it ends with something 
print(str.lower())# All lowercase 
print(str.upper())# Capitalize all 
st='hello world'
print(st[0])
print(str[::-1])# Output in reverse order 
print(st[2:5])# From the subscript 2 The beginning does not contain 5【 Left closed right away 】
print(st[2:])# From the third character to the last 
print(st[0:3])# from 0 At the beginning, you can omit 0
print(st[:3])

list

  • characteristic :
    ‘’’
    Support addition, deletion, modification and query
    The data in the list can be changed ,【 Data items can vary , The memory address doesn't change 】
    use [] To represent the list type , Data items are separated by commas , Be careful : Data items can be said to be of any data type
    ‘’’

list=[]# An empty list 
print(list)
print(len(list))# Get list object Number of data in 
str='lodsa'
print(len(str))
  • lookup

listA=['abcd',123,456,798,True,12.255]
print(listA)
print(listA[0])# Find the first element 
print(listA[1:3])
print(listA[3:])
print(listA[::-1])# flashback 
print(listA*3)# Output data in the list many times 【 Copy many times 】
  • add to

print('------------------ increase ---------------------')
listA.append('Jay')
listA.append([1,1,2,'dfgs',{
"al":12}])
print(listA)
listA.insert(1,' The elements inserted ')# The insert , You need to specify the insertion position 
# reData=list(range(10))# Coercive transformation list object 
listA.extend([12,45,484])# Expand , Batch addition 
print(listA)
  • modify
print('----------------- modify --------------')
print(' Before the change ',listA)
listA[0]='Peter'
print(' After the modification ',listA)
  • Delete

print('---------------------- Delete ---------------')
del listA[0] # Delete the first element in the list 
print(listA)
del listA[1:3]# Batch deletion 
print(listA)
listA.remove(798)# Indicate the specified element 
print(listA)
listA.pop(0)# Remove the first element # Remove by subscript 
print(listA)

Tuples

  • Tuples are immutable sequences , You cannot make any changes after creation

  • variable

  • use () To create tuple types , Data items are separated by commas

  • It can be of any kind

  • When there is only one element in a tuple , Add a comma , Otherwise, the interpreter will be treated as plastic

  • Slicing is also supported

  • lookup


tupleA=()# An empty list 
tupleA=('abcd',123,12.55,[123,45,'45hf'])
print(tupleA)
print(tupleA[2])
print(tupleA[1:3])
print(tupleA[::-1])
print(tupleA[::-2])
print(tupleA[-2:-1:])# Take the subscript upside down , -2 To -1 Interval data 
print(tupleA[-4:-1])
  • modify

tupleA[3][0]=250# Modify the list type data in tuples 
tupleB=tuple(range(10))
print(tupleB.count(9))

Dictionaries

  • Dictionary is not a sequence type , There is no concept of subscript , Is an unordered set of key values , Is a built-in advanced data type

  • A dictionary can store any object

  • Dictionaries are created in the form of key value pairs {key:value} Wrap with braces

  • When there is an element in the dictionary , According to the key , value Each element of the dictionary is composed of 2 Part of it is made up of : key : value

  • A safe way to access values get() Method , When we are not sure whether a key exists in the dictionary and want to get its value , have access to get() Method , You can also set the default value

  • Add dictionary data


dictA={
"pro":" Art major ","school":' Shanghai Academy of drama '}
dictA['name']=' Li Yifeng '
dictA['age']=29
print(dictA)
print(len(dictA))
print(dictA['name'])# Get value by key 
dictA['name']=' Jackie Chan '# Modify the value of the key 
print(dictA)
print(dictA.keys())# Get all keys 
print(dictA.values())# Get all values 
print(dictA.items())# Get all the keys and values 
for key,value in dictA.items():
# print(item)
print('%s value ==%s'%(key,value))
dictA.update({
'age':32})# to update Update when there is , Add... If it doesn't exist 
dictA.update({
"height":1.78})# add to 
print(dictA)
  • Delete

del dictA['name']
dictA.pop('age')
print(dictA)

There is a common way

#+ Merge 
strA=' Life is too short '
strB=' I use Python'
print(strA+strB)
List_A=list(range(10))
list_B=list(range(10,21))
print(List_A+list_B)
# * Copy 
print(strA*3,end=' ')
print(List_A*3)
# in Determines whether an object exists 
print(' I ' in strA)
print(10 in list_B)

Python function

master Python Function basis , Lay a solid foundation for the development project

First knowledge of function

  • In the process of programming , A function code block appears many times , But in order to improve the efficiency of writing and reuse of code , So organize the code blocks with independent functions into a small module , This is the function

  • It's a series Python The combination of sentences , You can run one or more times in a program ,

  • Generally, it has independent functions

  • Maximize code reuse and minimize redundant code , The overall code structure is clear , Problem localization

  • Function definition

    def Function name ():
    The body of the function 【 A series of statements , Represents an independent function 】
    Function call
    Define before calling
    Function name plus () You can call
    Function documentation :
    The first line of the function content can be carried out with a string Function description

  • Function definition


def pritInfo():
'''
This function is used to print small pieces of information
'''
# Function code block
print(' Xiao Zhang's height is %f'%1.73)
print(' Xiao Zhang's weight is %f'%130)
print(' Xiao Zhang's hobby is %s'%' Jay Chou ')
print(' Xiao Zhang's major is %s'%' Information security ')
  • function call
pritInfo()
  • Further output the information of different people , Solve the problem by passing in parameters

def pritInfo(name,height,weight,hobby,pro):
# Function code block 
print('%s His height is %f'%(name,height))
print('%s My weight is %f'%(name,weight))
print('%s My hobby is %s'%(name,hobby))
print('%s My major is %s'%(name,pro))
  • Call the information with parameters

pritInfo('peter',175,130,' Listen to the music ',' Desserts ')
pritInfo(' petty thief ',189,140,' Play the game ',' Software engineer ')

Function parameter

  • Parameter classification :

Required parameters , Default parameters 【 Default parameters 】, Optional parameters , Key parameters

  • Parameters : In fact, the function is to realize a specific function , Then, in order to get the data needed to realize the function
    In order to get external data
    def sum(a,b):# Formal parameters : Just a parameter in the sense of , When defining, it does not occupy the memory address

    sum=a+b
    print(sum)

  • Required parameters

When the function is called , The required parameter must be assigned
sum(20,15)#20,15 Is the actual parameter Actual parameters , Real parameters , Is the actual memory address
sum() You can't write it like that , Need to pass the cords

  • Default parameters 【 Default parameters 】

def sum(a=1,b=11):
print(a+b)
sum()
  • sum(10)# At call time , If not assigned , Just use the default value given when defining the function

  • Variable parameters ( When the number of parameters is uncertain , More flexible )

def getComputer(*args):
''' Calculate the cumulative sum '''
# print(args)
result=0
for item in args:
result+=item
print(result)
getComputer(1)
getComputer(1,2,3,4)
  • Keyword variable parameters
  1. ** To define
  2. In the body of the function The parameter keyword is a dictionary type ,key Is a string
# def Func(**kwargs):
# print(kwargs)
# Func(name=' Zhao song ')
# def Infofunc(*args,**kwargs): # Optional parameters must precede keyword optional parameters 
# print(args)
# print(kwargs)
# Infofunc(1,2)
# Infofunc(12,13,46,age=18)
  • receive N A digital , Find the sum of these numbers

def num(*args):
''' # Write function , receive N A digital , Find the sum of these numbers '''
result=0
for i in args:
result+=i
return result
a=num(1,2,2,2,2)
print(a)
  • Find the element corresponding to the odd digit of the incoming list or tuple , And return to a new list
def Func1(con):
''' Find the element corresponding to the odd digit of the incoming list or tuple , And return to a new list '''
listA=[]
index=1
for i in con:
if index%2==1:# Judge odd digits 
listA.append(i)
index+=1
return listA
# e=Func1([1,2,45,1,1,'as',{1,25,',hs'}])
e=Func1(list(range(1,11)))
print(e)
  • Check each of the incoming dictionaries value The length of , If it is greater than 2, So just keep the first two lengths , And return the new content to the caller ,PS: The data in the dictionary can only be strings or lists
def Func2(dic):
''' Check each of the incoming dictionaries value The length of , If it is greater than 2, So just keep the first two lengths , And return the new content to the caller ,PS: The data in the dictionary can only be strings or lists '''
result={
}
for key,value in dic.items():
if len(value)>2:
result[key]=value[:2]# Add new data to the dictionary 
else:
result[key]=value
return result
# call 
dicObj={
'name':' Zhang San ','hobby':[' Sing a song ',' dance ',' Programming '],'major':' Information security '}
print(Func2(dicObj))

Function return value

  • Concept : After the function is executed, it will return an object , If there is... Inside the function return, You can return the actual value , Otherwise return to None
  • type : You can return any type , The type of return value should depend on return The latter type
  • purpose : Return data to the caller
  • There can be more than one... In a function body return , But there must be only one return
  • If in a function body , Yes return, It means that the implementation is completed ,return Later code will not execute
# Return value 
def Sum(a,b):
sum=a+b
return sum # Return the calculation result to 
result=Sum(12,15)# Assign the returned value to other variables 
print(result)
def calComputer(num):
''' Cumulative sum '''
listA=[]
result=0
i=1
while i<=num:
result+=i
i+=1
# listA.append(result)
listA.append(result)
return listA
message=calComputer(10)
print(type(message))
print(message)
def returnType():
''' Returns tuple type data '''
return 1,2,3
a =returnType()
print(type(a))
print(a)
def returnType1():
''' Return dictionary type '''
return {
"name":" Jackie Chan "}
b=returnType1()
print(type(b))
print(b)

Nested function

def fun1():
print("------------------fun1start")
print("-------------------- Execute code omission ")
print("-------------------fun1end")
def fun2():
print('------------------fun2start')
# Call the first function 
fun1()
print("---------------------fun2end")
fun2()
# The function classification : According to the function return value and function parameters 
# There are parameters and no return values 
# There are parameters and return values 
# No parameter, no return value 
# No parameter has a return value 

Function global variables

  • local variable : It's a variable defined inside a function 【 The scope is limited to the interior of the function 】
  • Different functions , You can define the same local variable , But each uses its own No impact .
  • The role of local variables : In order to save data temporarily , It needs to be defined in the function to store .
  • When global variables and local variables are defined repeatedly , The program will give priority to the internal variables defined by the function .
  • If you want to modify the global variables inside the function , You have to use global Keyword to declare .

# pro=' Information security '# Global variables 
# name=' Chow yun-fat '
# def printInfo():
# name=' Lau Andy '# local variable 
# print('{}'.format(name))
#
# def TestMethod():
# name='peter'# local variable 
# print(name)
# printInfo()
# TestMethod()
#
#
# def message():
# print(pro)
#
# message()
#
pro='123'
def changGlobal():
global pro
pro='456'
print(pro)
changGlobal()

quote

  • stay Python in , Value is transmitted by reference , It can be used id() Check whether the references of an object are the same .

  • id Is the identification of the memory address where the value is stored in memory .

  • Immutable type

a=1
def func(x):
print('x The address of {}'.format(id(x)))
x=12
print(' Modified x The address of :{}'.format(id(x)))
print('a The address of :{}'.format(id(a)))
func(a)
  • Variable type

li=[]
def testRenc(parms):
print(id(parms))
li.append([1,2,3,54])
print(id(li))
testRenc(li)
print(' External variable object {}'.format(li))
  • Summary
  1. python in , Everything is object , When a function is called , The argument passes a reference to the object ,
  2. After understanding the principle , You can better control , Whether the processing inside the function will affect the changes of external data
  3. Parameter passing is done by object reference Parameter passing is done by object reference Parameter passing is done by object reference

Anonymous functions

  • grammar

lambda Parameters 1、 Parameters 2、 Parameters 3: expression

  • characteristic

    • Use lambda Keyword creation function
    • Functions without names
    • The expression after the colon of an anonymous function has only one , Be careful : Is an expression , Instead of statements
    • Anonymous function comes with return, And this return The result of is the result of expression calculation
  • shortcoming

    • lamdba It can only be a single expression : Not a code block ,lamdba Is designed to meet simple function scenarios
    • Can only encapsulate limited logic , Complex logic cannot achieve , You have to use def To deal with it
# Anonymous functions 
m=lambda x,y:x+y
# Call anonymous functions through variables 
print(m(23,19))
M=lambda a,b,c:a*b*c
print(M(1,2,3))
age =15
print(' You can continue to join the army ,'if age>18 else' Keep going to school ')
C=lambda x,y:x if x>y else y
print(C(1,5))
re=(lambda x,y:x if x<y else y)(16,12)
print(re)
Rs=lambda x:(x**2)+890
print(Rs(10))

Recursive function

If a function does not call other functions internally , But call yourself , This function is a recursive function

recursive Call yourself
There must be a clear end condition

  • Factorial / By recursion
# Factorial / By recursion 
def factorial(n):
''' Factorial '''
if n==1:
return 1
return n*factorial(n-1)
result =factorial(5)
print(result)
  • Factorial through ordinary functions
# Factorial through ordinary functions 
def jiecheng(n):
''' Factorial '''
result=1
for item in range(1,n+1):
result*=item
return result
re=jiecheng(5)
print(re)
# Simulation Implementation , Traversal of tree structure 
import os # Introduce file operation module 
def findFile(file_Path):
listRs=os.listdir(file_Path)# Get the folder under the path 
for fileItem in listRs:
full_Path=os.path.join(file_Path,fileItem)# Get the complete file path 
if os.path.isdir(full_Path):# Determine whether it is a folder 
findFile(full_Path)# If it's a file , Go over again 
else:
print(fileItem)
else:
return
#d Call search file object 
findFile('D:\\Python')

Built in functions Mathematical operations

#Python Functions that come with language 
print(abs(-23))# Take the absolute value 
print(round(2.23))# Approximate value 
print(round(12.56,1))# Keep one decimal place 
print(pow(3,3))# Power 
print(3**3)# Power 
print(max(12,15,18))# Return maximum 
print(min(12,15))# minimum value 
print(sum(range(50)))
#eval Execute expression 
a,b,c=1,2,3
print(' Dynamically generated functions {}'.format(eval('a+b+c')))

Type conversion function

#chr() Number to character 
#bin() Change to binary 
#hex() To hexadecimal 
#oct() To octal 
#list() Convert tuples to list 
print(bin(10))
print(hex(16))
tupleA=(132,2,2,23,1)
print(list(tupleA))
listA=[1,123,15,',ghdj']
print(tuple(listA))
# bytes transformation 
print(bytes(' I like Python',encoding='utf-8'))

Sequence operation function

#sorted() Function to sort all objects that can be iterated Generate a new one to sort 
#sort() Sort based on the original data 
#all()
#range()
list=[1,2,3,45,6]
# list.sort()# Modify the original object directly 
print('------------- Before sorting -----------{}'.format(list))
# varList=sorted(list)
varList=sorted(list,reverse=True)# null 
# varList=sorted(list,reverse=False)# Ascending sort 
print('------------- After the sorting -----------{}'.format(varList))

set aggregate

#set Index slicing is not supported , Is an unordered and non repeating container 
# It's like a dictionary , But only Key, No, value
set1={
1,2,3}
set1.add(123)# Add operation 
set1.clear() # Empty 
print(set1)
List1=['1','2','24']
set2=set(List1)
print(set2)
re=set1.difference(set2)# Difference set , a In some b Not found in 
print(re)
print(set1-set2)# Difference set 
print(set1.intersection(set2))# intersection 
print(set1&set2)# intersection 
print(set1.union(set2)) # Combine 
print(set1 | set2)# Combine 
#pop Is to take data from the set and delete it at the same time 
print(set1)
set1.pop()
print(set1)
set1.discard(3)# Specifies to remove the element 
print(set1)
#update Two sets 
set1.update((set2))
print(set1)

Python object-oriented

Introduce Python Object oriented development , Lay a solid foundation for the development project

oop Introduce

object-oriented programming oop 【object oriented programming】 It's a kind of Python Programming ideas

  • Process oriented :
    When thinking about problems , How to follow the steps to achieve ,
    Then divide the problem solving into several steps , And these steps correspond to the final function of the method step by step

  • Process oriented : Is the beginning of learning , Follow the problem-solving steps to write code 【 Write code according to business logic 】

  • object-oriented : Focus on design thinking 【 Find a car wash , Pay for the car wash 】

  • From a computer perspective : Process oriented is not suitable for large projects

  • Process oriented focuses on : How do you do it?

  • Object oriented focuses on : Who will do it


Classes and objects

  • class : It's a template , The template contains multiple functions , Functions to achieve some functions

  • object : Instance created from template , Function in class can be executed through instance object

  • Class by 3 Part of the form :

    • The name of the class : Class name
    • Attributes of a class : A set of data
    • Class method : Method to allow operation on ( Behavior )

for example : Create a human being
The name of the thing ( Class name ): people (Person)
attribute : height , Age
Method ; eat run …

  • A class has a set of Having the same or similar characteristics 【 attribute 】 And behavior 【 Method 】 A collection of objects

Real world Computer world
Behavior ------》 Method
features ------》 attribute

  • object : It's a real thing , Concretization of classes Instantiation
  • A class is an abstraction of an object Objects are instances of classes

Defining classes

# Define classes and objects
# Class name : Name it in the way of big hump


# Create objects 
# Object name = Class name ()
''' class Class name : attribute Method '''
# Example method :
# Inside the class , Use def Keyword can define an instance method , And general functions Different definitions , Class method must contain parameters self【self It can be other names , But this position must be occupied 】, And it's the first parameter 
# attribute : In class Internally defined variables 
# Defined in class , The attributes outside the method become class attributes , The definition is used in the method self The referenced properties are called instance properties 
class Person:
''' The characteristics of the corresponding person '''
name=' Xiaoyong ' # Class properties 
age=22 # Class properties 
''' Corresponding person's behavior '''
def __int__(self):
self.name = ' Xiao zhao '# Instance attributes 
def eat(self):# Example method 
print(' Devour ')
def run(self):# Example method 
print(' Run fast ')
# Create objects 【 Class instantiation 】
xm=Person()
xm.eat()# Call function 
xm.run()
print('{} The age of {}'.format(xm.name,xm.age))

__init__ Method

# If there is n Such an object Be instantiated , Then you need to add instance attributes many times , Obviously it's more troublesome 
class Person1:
def __init__(self):# Magic methods 
''' Declaration of instance properties '''
self.name=' Xiaoyong '
self.age=22
self.sex=' schoolboy '
def run(self):
print(' Running too fast ')
xy=Person1()
# xy.run()
print(xy.age)

self understand

  • self And object point to the same address , It can be said that self It's a reference to an object
  • When instantiating an object ,self No developer reference is required ,Python Automatically pass objects to self
  • self It only makes sense when an instance method is defined in a class , There is no need to pass in the corresponding parameters when calling ,
  • Instead, the interpreter automatically points to
  • self The name of can be changed , Can be defined as other names , But the conventional definition has become self
  • self Refers to the class instance object itself
class Person:
def __init__(self,pro):
self.pro=pro
def geteat(s,name,food):
# print(self)
print('self Address in memory %s'%(id(s)))
print('%s Like to eat %s, The major is :%s'%(name,food,s.pro))
zs=Person(' psychology ')
print('zs Memory address of %s'%(id(zs)))
zs.geteat(' Xiao Wang ',' durian ')

Magic methods

Magic methods : __ xxx __


''' __init__ Method : Initialize a class , Use... When creating an instance object and assigning values to it __str__ Method : When converting an object to a string str( object ) When it comes to testing , Print the information of the object __new__ Method : Create and return an instance object , Called once , You get an object __class__ Method : Get classes of known objects ( object __class__) __del__ Method : This method is called when the object is destroyed after the program runs , To release resources '''
class Animal:
def __init__(self,name,color):
self.name=name
self.color=color
print('--------init-------')
def __str__(self):
return ' My name is %s, My color is %s'%(self.name,self.color)
def __new__(cls, *args, **kwargs):
print('--------new-------')
return object.__new__(cls)
dog =Animal(' Wangcai ',' black ')
print(dog)
''' __new__ and __init__ Function difference __new__ Class instantiation method : The instance must be returned Otherwise, the object will not be created successfully __init__ Used to initialize data properties , It can also be considered as the construction method of the instance , Receive an instance of the class self And construct it __new__ At least one parameter is cls Represents the class to be instantiated , This parameter is instantiated by Python The interpreter operates automatically __new__ The function must be executed before __init__ function '''

destructor


''' When an object is deleted or destroyed ,python The interpreter will call a method by default , This method is __del__() Method , Also known as the destructional method '''
class Animals:
def __init__(self,name):
self.name=name
print(' This is the construction initialization method ')
def __del__(self):
print(' When under a scope , Without being quoted , The interpreter will automatically call this function , To free up memory space ')
print(' This is the deconstruction method ')
print('%s This object is completely cleaned up , Memory space has been freed '%self.name)
cat=Animals(' Cat and cat ')
# del cat # Manually clean up and delete objects 
input(' Program waiting ......')
# When the whole program script is executed, it will automatically call _del_ Method 
# It will also be called automatically when the object is destroyed manually _del_ Method 
# Deconstruction methods are generally used for resource recovery , utilize _del_ Method to destroy an object and reclaim memory resources 

Single inheritance

Python Show three types of object-oriented : encapsulation , Inherit , many
state

  1. encapsulation : It's worth encapsulating the content somewhere , It is convenient for later use
    He needs to :
    Encapsulate the content somewhere , Go from another place to call the encapsulated content
    For encapsulation , In fact, it is to use the initialization construction method to encapsulate the content into the object , And then through the object directly or self To get the encapsulated content

  2. Inherit : It's the same as inheritance in real life , That is, the son can inherit the content of the father 【 Attributes and behaviors 】( Some fathers have sons , contrary , Some sons have fathers, not necessarily ),

  3. Polymorphism , The type of definition time is different from that of runtime , This is called polymorphism


class Animal:
def eat(self):
''' eat '''
print(' eat ')
def drink(self):
''' drink '''
print(' drink ')
class Dog(Animal):# Inherit Animal Parent class , here Dog It's a subclass 
def wwj(self):
print(' bark ')
class Cat(Animal):
def mmj(self):
print(' mews ')
d1=Dog()
d1.eat()# Inherited the behavior of the parent class 
d1.wwj()
c1=Cat()
c1.drink()
c1.eat()
''' For object-oriented inheritance , In fact, it is to extract the methods common to multiple subclasses into the parent class , Subclasses only need to inherit from the parent class without having to implement them one by one This can greatly improve efficiency , Reduce code duplication , Streamline the hierarchy of code To facilitate extension class Class name ( Parent class ): pass '''

Multiple inheritance

class shenxian:
def fly(self):
print(' Gods can fly ')
class Monkey:
def chitao(self):
print(' Monkeys like to eat peaches ')
class SunWuKong(shenxian,Monkey):
pass
swk=SunWuKong()
swk.fly()
swk.chitao()
# When the same method exists in multiple parent classes ,
class D:
def eat(self):
print('D.eat')
class C(D):
def eat(self):
print('C.eat')
class B(D):
pass
class A(B,C):
pass
a=A()
# b=B()
a.eat()
print(A.__mro__)# You can inherit the relationship of real classes in turn Find the execution order 
# In execution eaet When the method is used , The order should be 
# First of all to A Go inside , If A There is no , Then go on B Class to find , If B There is no , Then go C Search for ,
# If C Not in class , Then go D Search in class , If you haven't found it yet , You're going to report a mistake 
#A-B-C-D It's also the order of inheritance 

Override parent method

  • Rewrite , In the subclass , There is a method with the same name as the parent class , Methods in subclasses will override methods with the same name in subclasses ,
  • Why rewrite , The methods of the parent class can no longer meet the needs of the child class , Then the subclass can override the parent class or improve the parent class method

class Father:
def smoke(self):
print(' Smoke the lotus King ')
def drink(self):
print(' Drink Erguotou ')
class Son(Father):
# With the father ( smoking ) The method has the same name , This is overriding the parent method 
def smoke(self):
print(' Smoke Chinese ')
# After overriding the parent method , When a subclass calls a parent method , What will be called is the subclass method 
son=Son()
son.smoke()

polymorphic

  • Polymorphism , The type of definition time is different from that of runtime , This is called polymorphism

# To achieve polymorphism , There must be two premises to be observed :
''' 1. Inherit : Polymorphism must be released between parent and child classes 2. rewrite : Subclasses override methods of the parent class '''
class Animal:
''' Base class [ Parent class ] '''
def say(self):
print(' I'm an animal '*10)
class Dark(Animal):
''' Subclass 【 Derived class 】 '''
def say(self):
''' Override parent method '''
print(' I am a duck '*10)
class Dog(Animal):
def say(self):
print(' I am a '*10)
# dark=Dark()
# dark.say()
# Call uniformly 
def commonInvoke(obj):
obj.say()
list=[Dark(),Dog()]
for item in list:
''' Loop function '''
commonInvoke(item)

Class properties and instance properties

  1. Class properties : Is the attribute owned by the class object , It is shared by instance objects of all class objects , Class objects and instance objects can access

  2. Instance attributes : Properties owned by the instance object , Can only be accessed through instance objects


class Student:
name =' The dawn '# Belongs to class attribute , Namely Student Class objects have 
def __init__(self,age):
self.age=age # Instance attributes 
lm=Student(18)
print(lm.name)
print(lm.age)
print(Student.name)# adopt Student Class object access name attribute 
# print(Student.age)# Class objects cannot access instance properties 
# Class objects can be accessed and used by class objects and instance objects 
# Instance objects can only be accessed by instance objects 

Class methods and static methods

  • The first parameter of a class method is a class object cls, adopt cls The properties and methods of the referenced class object
  • The first parameter of the instance object is the instance object self, adopt self It's possible to refer to class properties , It could be Instance attributes
    , But in the case of class properties and instance properties with the same name , Instance properties have higher priority
  • No additional parameters need to be defined in static methods , So if you reference a class property in a static method , Must refer to... Through class objects

class People:
country='china'
@classmethod # Class method use classmethod To embellish 
def get_country(cls):
return cls.country# Access class properties 
@classmethod
def change_country(cls,data):
cls.country=data# Modify the value of column attribute , In the class method 
@staticmethod
def gatData():
return People.country
@staticmethod
def add(x,y):
return x+y
print(People.gatData())
p=People()
print(p.gatData())# Be careful : In general , We will not access static methods through instance objects 
print(People.add(1,2))
# print(People.get_country())# Refer to... Through class objects 
# p=People()
# print(' Access through instance objects ',p.get_country())
# People.change_country(' The British ')
# print(People.get_country())
# Because static methods are mainly used to store logical code , It does not interact with classes and instance objects 
# in other words , In a static method , It will not involve the operation of methods and properties in the class 
# Data resources can be effectively and fully utilized 
import time
class TimeTest:
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
@staticmethod
def showTime():
return time.strftime('%H:%M:%S',time.localtime())
print(TimeTest.showTime())
# t=TimeTest(2,10,11)
# print(t.showTime())# There is no need to access static methods through instance objects 

Privatization properties

  • grammar :

    • Start with two underscores , Declare the property private , Can't be used outside of the class or accessed directly
  • Scenarios using privatized attributes

    1. Hide a specific attribute , I don't want to make direct calls outside the class
    2. I want to protect this property , Don't want the value of the attribute to change at will ,
    3. Protect this property , Don't want derived classes 【 Subclass 】 To inherit
  • To access private variables, you usually write two methods , A visit , A modification , Access is controlled by methods

class Person:
__age =18 # Instance a privatized attribute , Attribute names are preceded by two underscores
‘’’


class Person:
__hobby = 'dance'
def __init__(self):
self.__name = ' Li Si ' # Add two underscores to privatize this property , No more direct external access , It can be accessed inside the class 
self.age = 30
def __str__(self):
return '{} The age of {}, like {}'.format(self.__name, self.age, Person.__hobby) # Call the privatization property 
def change(self, hobby):
Person.__hobby = hobby
class Studeng(Person):
def printInfo(self):
# print(self.__name)# Cannot access private properties in the parent class 
print(self.age)
pass
xl = Person()
# print(xl.name)# By class object , Externally accessible 
print(xl)
xl.change(' Sing a song ') # Change the value of the private property 
print(xl)
stu = Studeng()
stu.printInfo()
stu.change('Rap')
print(stu)
# print(xl.hobby) # Access class properties through instance objects 
# print(stu.hobby) # Access class properties through instance objects 
# print(Person.hobby) # Access class properties through class objects 

‘’’

  • Summary :
    1. Privatized 【 example 】 attribute , Cannot be accessed directly from the outside , You can use it freely inside the class
    2. A subclass cannot inherit the privatized property of a parent class ,【 You can only inherit properties and behaviors common to the parent class 】
    3. Add... Directly in front of the attribute name __, It can be privatized
      ‘’’
  • Underline Double underline , Double underline the head and tail

_xxx Underline before , Beginning with a single underscore indicates protected Variable of type , That is, the protection type can only be accessed by itself and its subclass , Out of commission from xxx import * How to import
__xxx__ Two underscores before and after , Magic methods , It's usually python Self contained , Developers should not create this type of method
xxx_ Single underline on the back , Avoid attribute names and Python Keyword conflict


Privatization methods

  • summary
    • The privatization method is the same as the privatization attribute , There are some important ways , External calls are not allowed , Prevent subclasses from accidentally overriding , Set the ordinary method as the privatization method
    • Privatized methods are usually called inside a class , Subclasses cannot inherit and cannot be called externally
  • grammar

class A:
def __myname(self): # Precede the method name with two underscores
print(‘ Xiao Ming ’)


class Animal:
def __eat(self):
print(' Eat something ')
def run(self):
self.__eat() # Call the privatization method here 
print(' Run fast ')
class Bird(Animal):
pass
bird = Bird()
bird.run()

Property function

# Property function (property)
class Perons:
def __init__(self):
self.__age = 18
def ger_age(self):# Access private instance properties 
return self.__age
def set_age(self, age):# Modify private instance properties 
if age < 0:
print(' Too young ')
else:
self.__age = age
# Define a class property , The implementation accesses private properties in the form of direct access to properties 
age=property(ger_age,set_age)
p=Perons()
print(p.age)
p.age=-1
print(p.age)

File operation and garbage collection mechanism

Learn to use Python Operation file , understand Python Garbage collection mechanism

  • File operations :
    1. Open file :open()
    2. WriteFile=open(“./Test.text”, mode=“w”,encoding=“utf-8”)
  • read / Write operations
    1. WriteFile.write(“ In the vast sea ”)
    2. WriteFile.write(“ Hello China ”)
  • Close file
    1. WriteFile.close()

Write data in binary form


''' fobj=open("./Test1.text","wb")# str--->bytes fobj.write(" Between the dark clouds and the sea ".encode("utf-8")) fobj.close() '''

The binary form is appended

''' # Additional not required encode() #fobj=open("Test.text","a")# Additional data #fobj.write(" Between the dark clouds and the sea \r\n") #fobj.write(" Petrels are like black lightning \r\n") fobj=open("./Test1.text","ab")# str--->bytes fobj.write(" Today, poetry is booming \n".encode("utf-8")) fobj.close() '''

Read file data

#fobj=open('./Test.text','r')
fobj=open('./Test.text','rb')
data=fobj.read()
print(data)
print(data.decode("utf-8"))# Read all data 
#print(fobj.read(12))# Read two data 
#print(fobj.readline())# Read a row of data 
#print(fobj.readlines())# Read all lines , Returns a list of 
fobj.close()# The file object is closed 
  • with sentence , Whether or not an exception occurs during file processing , Can guarantee with After the statement is executed, the open file handle has been closed
  • with Context management object
  • advantage : Automatically release associated objects
with open("withfile.text",'r') as f:
#f.write("123 Wooden man ")
print(f.read())
  • read r r+ rb rb+
  • r r+ read-only , Suitable for common reading scenarios
  • rb rb+ apply file , picture , video , Read files like audio
  • write w w+ wb wb+ a ab
  • w wb+ w+ Every time a file is created
  • Pay attention to coding when reading and writing binary , By default , The write file code is gbk
  • a ab a+ Add ,【 End of file pointer 】, Not every time a new file is created

Regular expressions

Learn regular expression operation string
re The module is to use C The language doesn't match, and the speed is very fast
among compile Function to generate a regular expression object based on a pattern string and optional flag parameters , This object has a series of methods for regular table assembly matching and replacement ,re The module also provides functions that are completely consistent with the functions of this method , These functions apply a pattern string as their first argument

re.macth Method

  • re.math Try Match from the beginning of the string , return match object ,, Otherwise return to None, apply group() Get the string that matches successfully
    • grammar :re.match(pattern,string,flags)
Parameters describe pattern Matching regular expressions string String to match flags Sign a , Used to control how regular expressions are matched : Such as : Match case , Multi-line matching
import re
str='Python is the best language in the world'
result= re.match('P',str)
print(type(result))#<class 're.Match'>
print(result.group())

Sign a

  • If multiple flag bits are used , Use | Division , Such as :re.I|re.M
Modifier describe re.I Case insensitive matching re.L Do localization recognition match re.M Multi-line matching , influence ^ and $re.S send . Match all characters including line breaks re.U according to Unicode Character set parsing characters , This sign affects \w,\W ,\b,\Bre.X This identifier gives you a more flexible format so that you can write regular expressions easier to understand .
import re
strData='Python is the best language in the world\
gslfjgldsjgls'
#result= re.match('p',strData,re.I|re.M)# The third parameter Ignore case 
#print(type(result))#<class 're.Match'>
#print(result.group())
res=re.match('(.*?)is(.*?)',strData,re.I)
print(res.group(1))
print(res.group(2))

Common matching rules

Symbol Matching rules .( spot ) Match arbitrarily 1 Two characters, except for line breaks [abc] matching abc Any one of \d Match a number 0-9\D Match non numeric \s Match blanks That is, the space tab key \S Match non spaces \w Match word characters namely a-z A-Z 0-9 _\W Match non word characters

Number of matching characters

Symbol Matching rules * Match previous character appears 0 Times or infinite times , You can have it or not + Match previous character appears 1 Times or infinite times , At least 1 Time ? Match previous character appears 1 Time or 0 Time , That is to say, there is either 1 Secondary? No {m} Match previous character appears m Time {m,} Match the previous character at least m Time {m,n} Match previous character appears from m Time to n Time

Limit matching quantity rule


import re
# * Match previous character appears 0 Times or infinite times 
res=re.match('[a-z][a-z]*','MyPython',re.I)
print(res.group())
# + Match the previous character 1 Times or infinite times At least once 
res=re.match('[a-zA-Z]+[\w]*','mynAMEDCeisz848s_')
print(res.group())
# ? Match the previous character 0 Time or 1 Time 
res=re.match('[a-zA-Z]+[\d]?','mkohjhjgu8jg8')
print(res.group())
# {min,max} Match the previous from min To max Time min max Must be a non negative integer 
#{count} The exact number of matches {count,} There is no limit to 
res=re.match('\d{4,}','46145')
if res:
print(' The match is successful {}'.format(res.group()))
# Match mailbox Format :[email protected]
res=re.match('[a-zA-Z0-9]{6,11}@163.com','[email protected]')
print(res.group())

Native string

# path="D:\\1_zhao_File\\1_MarkDown\MarkDown Learn to use "
# print(path )
import re
# Native string r
print(re.match(r'c:\\a.text','c:\\a.text').group())
# Match the beginning and the end 
#^ Match the beginning of a string 
#$ Match string end 
# res=re.match('^p.*','python is language')
res=re.match('^p[\w]{5}','python is language')
print(res.group())
res=re.match('[\w]{5,15}@[\w]{2,5}.com$','[email protected]')
print(res.group())

Packet matching


# | Match any expression left or right From left to right 
import re
res=re.match('[\w]*|100','100')
print(res.group())
# (ab) Packet matching Use the characters in brackets as a group 
res=re.match('([0-9]*)-(\d*)','123456-464651561')
print(res.group())
print(res.group(1))
print(res.group(2))
# \num Use 
# htmlTag='<html><h1>Python Programming core </h1></html>'
# res1=re.match(r'<(.+)>(.+)>(.+)</\2></\1>',htmlTag)
# print(res1.group(1))
# grouping The use of aliases (?P< name >)
data='<div><h1>www.baidu.com</h1></div>'
res=re.match(r'<(?P<div>\w*)><(?P<h1>\w*)>(?P<data>.*)</\w*></\w*>',data)
print(res.group())

Compile function


# re.compile Method 
''' compile Compile the regular expression pattern into a regular expression object reg=re.compile(pattern) result=reg.match(string) Equivalent to result=re.match(pattern,string) Use re.compile And keep the resulting regular expression object reuse efficiency higher '''
import re
#compile You can compile strings into bytecodes 
# advantage : When using regular expressions match when ,python Will convert the string to a regular expression object 
# And if you use compile, You only need to convert once , There is no need to repeat the conversion when using schema objects in the future 
data='1364'
pattern=re.compile('.*')
# Use pattern object 
res=pattern.match(data)
print(res.group())
#re.search Method 
#search Match once in the full text , Match to return 
data=' I love my great motherland ,I love China,China is a great country'
rees=re.search('China',data)
print(rees)
print(rees.span())
print(rees.group())
# print(data[21])
#re.findall Method Match all , Return a list ,
data=' Huawei is the pride of Chinese '
# res =re.findall(' Hua .',data)
# print(res)
pattern=re.compile(' Hua .')
res=pattern.findall(data)
print(res)
# re.sub Method Realize target search and replacement 
data1='Pythons Is a very popular programming language '
pattern='[a-zA-Z]+' # Character set range + representative Leading character mode appears 1 From above 
res=re.sub(pattern,'C#',data1)
resn=re.subn(pattern,'C#',data1)
print(res)
print(resn)
#re.subn Complete the search and replacement of goals It also returns the quantity replaced , Returns... As a tuple 
#re.split Is the new split string 
data=' Baidu , tencent , Ali , Huawei ,360, Bytes to beat '
print(re.split(',',data))

Greedy mode and non greedy mode

''' python The default is greedy , Always greedily match as many characters as possible , Not greedy, on the contrary , Always try to match as few characters as possible stay ” * ? + {m,n}" Followed by ? To turn greed into non greed '''
# greedy 
import re
res=re.match('[\d]{6,9}','111222333')
print(res.group())
# Not greed 
res=re.match('[\d]{6,9}?','111222333')
print(res.group())
content='asdfbsdbdsabsd'
# pattern=re.compile('a.*b')# greedy 
pattern=re.compile('a.*?b')# Not greed 
res=pattern.search(content)
print(res.group())
#0710-49

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved