python basics

Data type acquisition type() function, isinstance() function

join join string method "_".join("string to be added");
ljust left-align the content, fill with
lower on the right make the string lowercase
lstrip remove the space on the right
rstrip remove the space on the right
strip remove all The space
replace replaces s.replace("al","bb",1); rfind finds rsplit()
from right to left to split the string swapcase uppercase to lowercase, lowercase to uppercase startwith starts with .... upper( ) to uppercase the verification code can be used



列表
name_list=["a",'b','c']
#索引
print(name_list[0])
#切片
print(name_list[0:2])
#len
print(name_list[0:len(name_list)])
for i in name_list
print(i)

#Additional functions provided inside the list

append append
name_list.append('senven'), that is, add a string at the
end name_list.count('senver') to find
the number #iterable iterable
name_list.extend() pass a list to another list, that is, batch process
name_list .insert(1,'SB'); insert
name_list.remove('seven') at position 1 remove the first seven
nem_list.reverse() invert the list
name_list.sort() to sort

Tuples are not modifiable

dictionary


user_info={
"name":"alex",
"age":72,
"gender":'M'
}

Each value has a key and a value #index
of the dictionary
print(user_info['name']) that is, the name is the index
. Since the key value of the dictionary is arbitrarily defined, there is no slice
#loop
for i in user_info:
print(i ) #Get
all keys
print(user_info.keys()) #Get
all values
​​print(user_info.values()) #Get
all key-value pairs
print(user_info.items())
print(user_info.clear()) Empty the dictionary
val=user_info.get('age','123') According to the key value, if the key value does not exist, you can specify a default value, so it is recommended to use get instead of index


Check that agf is in the key that is not in the dictionary
ret='agf' in user_info.keys()
print(ret)#The output bool value
A dictionary can use update to update the content of one dictionary to another dictionary
del user_info['name '] delete the key-value pair of the specified index

 

New look

Index # can only find one s[1]
slice # can find multiple s1[1:4]
encoded in UTF-8, one Chinese character, 3 bytes
bytes can convert characters into bytes
bin() method to output binary representation

i="郭振东"
for b in i:
print(b)
bytes_list=bytes(b,encoding='utf-8')
#print(bytes_list)
for c in bytes_list:
print(c,bin(c))

#Represent your name in binary
#insert Insert the specified element to the specified position


#If there is a dictionary dic={'k1':'v1'}
dic.update({'k2':123})
dic['k2']=123

Sorting:
general string, perform a function, generate a new content, the original content does not change
list, tuple, dic, perform a function, change itself
enumerate(li) # enumerate list or string function

 

#set A set that does not allow duplicates can be understood as a list that does not allow duplicates
1. Create
s=set()
s={11,12,31}
2. Convert
s=set(list name)
3. The method provided by set
se= {11,122,33}
print(se)
se.add(44)#Add
print(se)
#se.clear()#Clear
print(se)

be={11,66}
t=se.difference(be)#Find the elements that exist in se but the elements that do not exist in be, and assign them to t
print(t)
se.difference_update(be)#Find the elements where se exists and be non-existent element, and update itself
print(se)

#Trinary operation, ternary operation

#For example, the name=if condition in C language? Value 1: Value 2
#In python name=value 1 if condition else value 2 value 1 is the value that the condition is true, value 2 is the value that is not true
name="cc" if 1==1 else "dd"
print( name)


#Instance of sending email
def email(p):
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
try:
msg = MIMEText("This is", 'plain', 'utf-8')
msg[ 'From'] = formataddr("Wu Peiqi", '[email protected]')
msg['To'] = formataddr(["Leave", "[email protected]"])
msg['Subject'] = 'Subject'
server = smtplib.SMTP("smtp.126.com", 25)
server.login("[email protected]", '372930gzd')
server.sendmail('[email protected]', [p, ], msg.as_string())
server.quit()
return True
except:
return False

rr=email('[email protected]')
if rr:
print("Send successfully")
else:
print("Send failed")

#--------end


#Definition form of the default value of the function
def drive(name="Guo Zhendong")
##If no parameters are passed, Guo Zhendong is the default, and parameters with default values ​​must be placed after no default parameters
def drive(*args,* *kwargs)
*, tuple, element of tuple
**, dictionary

Pass in list, tuple, dictionary for dynamic arguments
*args*list
*kwargs**dictionary

#Deep and shallow copy
1, numbers, strings
, the same depth
2, others
Shallow copy: only copy the first layer
Deep copy: do not copy the last layer
#set collection
Unordered, non-repetitive, cannot use index to
find intersection, union, Difference
function
def
function name
Execute function
global variable and add a globable when using it


#python built-in functions

bin(11)#output binary
oct(11)#output octal
hex(11)#output hexadecimal
callable(name) is executable

li=[]
print(dir(li))
help(list)

divmod()#Use ******* when paging


a="1+3"
print(a)
ret=eval(a)#Convert the string into an expression and directly calculate the result
print(ret)

****#Random number
import random
for i in range(6):
ra=random.randrange(1,123)
print(ra)


#码
import random
temp = ""
for i in range (6):
li = random.randrange (0,4)
if li == 2 or li == 4:
ra2 = random.randrange (0,10)
temp+= str (ra2)
else:
ra = random.randrange (65, 91)
c1 = chr (ra)
temp+= c1
print (temp)


********
# f=open("haha","a")
# data=f.write(bytes("中国",encoding="utf-8"))
# f.close()
#文件的写入

#File read operation
f=open("haha","r",encoding="utf-8")
data=f.read()
f.close()
print(data)
******** ********************************Summary *****
Function name can be passed as parameter
function name()=="execution Function
function name == "refers to the function

Built-in function == "Screenshot
all() All elements are true before they are true
any() As long as one element is true, it is true
bin()10-->2
hex()10-->16
int() all Convert to 10
oct() 10->8 decimal to octal
bool() empty string, 0, None, empty tuple, empty dictionary, empty list
bytes() string to byte
chr() number to word Section
ord() and chr() in contrast to
dir() to quickly find the function
enumerate()? ? ? ?
eval() returns the value again


************************Summary end ****************


Actual Project ************************************************ *
split("$") splits the string with the $ sign

def login(name,pwd):
"""

:param name:
:param pwd:
:return:
"""
f = open("db", "r", encoding="utf-8")
for line in f:
line = line.strip()
line_list = line.split("$")
if name == line_list[0] and pwd == line_list[1]:
return True
return False

def register(name,password):
"""
Register user
1, open file a
2\username$password
:param name:
:param password:
:return:
"""
with open("db","a",encoding ="utf-8") as f:
temp="\n"+name+"$"+pwd
f.write(temp)
return True

def user_exist(user):
#验证用户是否存在
with open("db","r",encoding="utf-8") as f:
for line in f:
line = line.strip();
line_list=line.split("$")
if line_list[0]==user:
return True
return False


def main():
print("Wellcom XXX系统")
inp = input("1:登陆;2:注册")
if inp == "1":
name = input("input name")
pwd = input("input pwd")
if login(name, pwd):
print("success")
else:
print("fail")
elif inp == "2":
name = input("input name")
pwd = input("input pwd")
if user_exist(name):
print("用户存在,无法注册")
else:
if register(name, pwd):
print("注册成功")

main()


****************************End of the actual project landing **************** *
*
*
*
*
Basic Algorithms ************************

#Bubble Sort

li=[11,12,54,4,6,78]
for i in range(len(li)-1):
for j in range(i+1,len(li)):
if(li[i]<li[j]):
t=li[i]
li[i]=li[j]
li[j]=t

print (li)

#Fibonacci sequence

def fun(i):
if i==1:
return 1
elif i==2:
return 1
else:
return fun(i-1)+fun(i-2)


i=int(input("input:"))
print(fun(i))
****************结束******************

*
*

#python decorator theme ************************************************

Execute a function before or after the function is executed without changing the function content
def outer(func):
#func=original f1 function
def inner():
print("hello")
print("hello ")
print("hello")
r=func()
print("end")
print("end")
print("end")
return r

return inner


@outer #As
long as this sentence is executed, the outer function is executed, and the function name below it is used as a parameter, then f1=func
#2Reassign the return value of Outer to the return value of f1=outer
def f1():
print ("guozhendong")

f1 ()

 

1\define the decorator
2, apply the decorator @ decorator name

 

 

 

 

 

 

 


**************************************************** **********end

 

*************Regular Expressions ******
Character matching (normal characters, metacharacters)
12 metacharacters. ^ $ * + ? {} [] | () \
re.findall('alex.w','aaaaalexaw') #.Represents a placeholder
import re
>>> re.findall('^alex','alexajdkfj')

###The sharp angle character indicates that the query string can only be found at the beginning
re.findall('alex$','adfkjalex')
#### The $ character indicates that the query string can only be found at the end
re.findall('alex*','adfkjalex')
## The * sign indicates that the match for the last character can be without the last x, or there can be multiple x's, which can be queried to 0 or more

re.findall('alex+','adfkjalex')
## The * sign indicates that there can only be multiple x's to match the last character, and it can be queried to 1 or more
and? The number can only match 0 or 1


re.findall('alex{11}','adfkjalexxx')
{} can find a fixed number of strings, xxx can also be written as {3,5}


Character set:
re.findall('a[bc]d','abd')
This form can check the two cases of abd and acd

re.findall('a[.]d',"wwadd")
will lose its meaning at this time. Only the string containing ad can be found
. re.findall('a[az]d',"wwadd")# Find any lowercase letter, so the above list can be found, it can also be changed to [1-9]
re.findall('[^1-9]','wwwed5f54') This example will find all non-digits output, so the role of the sharp angle character is the meaning of right and wrong


The function of \ is to lose the function of meta-characters. If there are ordinary characters behind, special functions will be implemented\n that is line feed
re.findall('\d','www.3wddf0') output 3 0
re.findall('\ w','www.3wddf0') will output all characters
re.findall('\s','www .3wddf0') will output spaces

re.search("(ab)*","aba").group() can only match and find one
re.match("alex","abalexksdalex") only match whether there is a string at the beginning

re.search(r"a(\d+)","a4564").group()
re.search(r"a(\d+?)","a4564").group()
re.search(r"a(\d+*)","a4564").group()
******************结束*********

 


Review file operation ******Summary
open file operation
open()
1, file path
2, basic operation
r, read-only
w, write-only (clear first, then write)
x, if the file does not exist, first Create, if it exists, report an error: write only
a, append, write only
binary
rb
wb
xb
ab + #The plus sign means adding a new function r+
on the basis of the original function , read and write read, 0 starts to read and write, the position of the pointer Start writing , read first, append at the end Active seek, write backward from the current pointer, write w+, read and write x+, read and write a+, read and write







File operation *****
trancate, intercept the previous
read
write
str: no, string
bytes: yes, byte
readline: read only one line
readlines["first line", "second line"]
flush forcibly flush into the hard disk
close
tell() get the pointer position
seek() jump to a certain position
with open(xx) as f1, open(xx) as f2:

#####Decorator code summary learning
def xxx(args):
def sb():
print("sb")
r=args()
print("end")
return r
return sb
@xxx
def num():
print ("num")
return "num"
s=num()
print(s)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325045628&siteId=291194637