first, the number
numeric types contain integral , floating-point, and less commonly used long integers and complex numbers.
Second, string
Definition: in single quotation marks \ double quotes \ Three quotation marks, consisting of a string of characters
msg= ' Hello World '
1. Slicing
Print (Msg[1:8]) #从下标为1的字符开始取, Gu Tou regardless of the tail, so take the seventh character, so get Ello Wo, the space is also a character print (Msg[1:8:2]) #从下标为1的字符开始取, Gu Tou disregard the tail, so take to the seventh character, Step is 2, take a skip one, get El Oprint (msg[0]) #取出下标为0的字符, is the first character, get Hprint (Msg[-1]) #取出最后一个字符, get D
2. Length
Print (Len (msg)) #变量msg的字符串长度, get 11
3, member operations in and not in, see if the acquired character is in a variable-defined string
Print (' Llo ' in msg) # ' Llo ' is in the variable-defined string, so returns True
4, remove the blank strip
Name= ' **********hello*********** ' Print (Name.strip (' * ')) #去掉hello两边的 *print (Name.lstrip (' * ')) #去掉hello左边的 *prin T (Name.rstrip (' * ')) #去掉hello右边的 * #和用户交互常用的情况如下name =input (' User: '). Strip () #对用户输入的字符串去掉两边的空格print (name)
5. Segmentation
info= ' Root:x:0:0::/root:/bin/bash ' res=info.split (': ') #以冒号为分隔符对字符串进行分割, the split will become the form of the list res=info.split (': ', 1) #以冒号为分隔符对字符串进行分割, and specify the maximum number of splits to 1, convenient to remove the string before the first colon res=info.rsplit (': ', 1) #从右进行切分, slicing once, the result is to follow the last colon to cut the string into two parts
6. Circulation
For I in Range (0,5,2): #0到4之间, step 2, so get results 0 2 4 print (i)
7, Lower,upper
Print (' AbcD '. Lower ()) #把字符串全部显示成小写, the result is abcdprint (' AAA '. Upper ()) #把字符串全部显示成大写 and the result is AAA
8, Startswith,endswith
Msg= ' Tom is Boy ' Print (Msg.startswith (' Tom ')) #开头的是否是tom, returns True or FALSE, so returns Trueprint (Msg.startswith (' t ')) #开头的是 No is T, so return Trueprint (Msg.endswith (' Boy ')) #末尾的是否是boy, so return true
9. Join
l=[' root ', ' x ', ' 0 ', ' 0 '] ': '. Join (L) #把列表l里的元素通过冒号合并成一个字符串, the elements in the list L must be all strings, otherwise the error
10. Replace
Msg= ' Tom say my name is Tom ' Msg=msg.replace (' Alex ', ' leader ', 1) #用leader替换tom and replaces only one print (msg)
11, IsDigit judge whether it is a number
Age=input (' >>: '). Strip () if Age.isdigit (): #用户输入的是数字以后, convert it to integral type age=int (age) Else : Print (' must input number ') print (Age,type (age))
Third, List
1, definition: [] can have more than any type of value, comma separated
name=[' Zhao ', ' Qian ', ' sun ', ' Li ']
2. Methods Append and Extend,insert
Name.append (' ni ') #列表里添加元素nil =[' song ', ' Zhang ']name.extend (l) #列表里添加多个元素print (name) Name.insert (1 , ' Wang ') #插入元素wang, subscript 1
3. Method Index
Print (Name.index (' Zhao ')) #显示元素zhao对应的下标
4. Remove and pop
Name.remove (' Li ') #删除元素li, but does not take away the element print (name) Name.pop () #删除并拿到结果, takes a value
5. Circulation
For item in Name:print (item)
6. Clear
Name.clear () #清空列表
7. Copy
L=name.copy () #拷贝列表name, the result as the value of the variable L print (l)
8. Count
Print (Name.count (' Li ')) #统计元素li出现在列表里几次
9, Reverse
Name.reverse () #将列表name元素倒向显示, the result is [' Li ', ' Sun ', ' Qian ', ' Zhao ']
10. Sort order
L=[1,10,4,11,2,]l.sort () #对列表里的元素排序print (L) l.sort (reverse=true) #对列表里的元素倒向排序print (L)
Four, the tuple
1, compared with the list type, only [] replaced ()
Save multiple values, the tuple is immutable in comparison to the list, mainly for reading
Age= (11,22,33,44,55)
1. Index
Print (Age.index (one)) #取出元组里元素11对应得下标print (Age.index (3333)) # element does not exist times wrong ValueError:tuple.index (x): X not in Tupleprint (Age[0:3]) #取出元组里元素下标为0, sub-tuple
2, Length Len
Print (Len (age)) #得到元组元素的个数
3, member operations in and not in
Print (one-in-age) #判断元素11是否在元组里
4. Circulation
For item in Age:print (item)
5.Count
Print (Age.count) #判断元素33出现的次数
6, the realization of printing product details, the user entered the product name and purchase number, then the product name, price, purchase number added to the shopping list, if the input is empty or other illegal input requires the user to re-enter
msg_dic={' Apple ': Ten, ' Tesla ': 100000, ' Mac ':3000,}goods=[] #购物车, Prepare an empty list while true: for k in msg_dic: print (K,msg_dic[k]) choice=input (' name: '). Strip () if len (choice) ==0 or choice not in msg_dic: #如果用户输入字符为空或者输入的不是指定的商品, let the user re-enter continue while true: num= Input (' number: '). Strip () if num.isdigit (): break goods.append (( Choice,msg_dic[choice],int (num))) #注意括号容易少写 print (' Shopping cart ', goods)
Five, dictionary
1, definition: Key must be immutable type (int,float,str,tuple), value can be any type
info={' name ': ' Egon ', ' age ':, ' sex ': ' Male '}
2, Fromkeys
Info={}.fromkeys ([' Name ', ' age ', ' sex '],none) #快速创建字典, each element of the preceding list will be one element of the dictionary and None
3, modify the value of the dictionary
info[' age ']=22 #指定key, equals a value
4, Length Len
Print (len (info)) #判断字典的长度, which has several elements
5, member operations in and not in
Print (' name ' in info)
6. Delete Pop
Print (Info.pop (' name ')) #取出字典key为name的元素print (info) # See the key-value pairs with the element name have been deleted
7. Popitem and keys, values
Print (Info.popitem ()) #取出后面的键值对, the result is (' sex ', ' Male ') print (Info.keys ()) #取出字典里所有的key, the result is Dict_keys ([' Name ', ' Age ']) print (List (Info.keys ()) [1]) #取出字典里所有key的组合, go to the list, and then remove the corresponding key according to the subscript, the result is Ageprint (Info.values ()) #取出字典里所有的value, The result is that the dict_values ([' Egon ',]) print (List (info.values ()) [1]) #取出字典里所有value的组合, goes to the list, and then takes out the corresponding value according to the subscript, the result is 18print (list ( Info.items ()) [1]) #取出键值对, the final result is (' age ', 18)
8. Circulation
info={' name ': ' Egon ', ' age ': $, ' sex ': ' Male '}for K in info: #循环key, finally via key to values print (K,info[k])
9, the following values set [11,22,33,44,55,66,77,88,99,90], all values greater than 66 are saved to the first key of the dictionary, the value less than 66 is saved to the value of the second key
nums=[11,22,33,44,55,66,77,88,99,90]d={' K1 ': [], ' K2 ': []}for num in nums:if num > 66:d[' k1 '].append (num) i F num < 66:d[' K2 '].append (num) print (d)
Six, the collection
1. Definitions and principles
Collection: Can contain multiple elements, separated by commas
The elements of a collection follow three principles:
1: Each element must be an immutable type (hash, can be used as the dictionary key)
2: No duplicate elements
3: Unordered
pythons={' Alex ', ' Egon ', ' Yuanhao ', ' Tom ', ' Jim '}linuxs={' Tom ', ' Sam '
2. Length
Print (len (pythons)) #长度即是集合 the number of elements in Python, so 5
3, member operations in and not in
Print (' Alex ' in pythons) #判断alex是否在python集合中, so the result is true
4. Intersection
Print (Pythons & linuxs) #同时在两个集合中的元素, so the result is {' Tom '}
5. Collection
Print (Pythons | linuxs) #两个集合的所有元素, repeated display once, so the result is {' Tom ', ' Jim ', ' Egon ', ' Sam ', ' Alex ', ' Yuanhao '}
6. Difference Set
Print (PYTHONS-LINUXS) #python中的元素减去linuxs中的元素, the remaining result is {' Jim ', ' Yuanhao ', ' Egon ', ' Alex '}
7. Symmetrical difference Set
Print (pythons ^ linuxs) #没有同时在两个集合中的元素, that is, all elements minus the intersection result is {' Egon ', ' Sam ', ' Jim ', ' Alex ', ' Yuanhao '}
8. Parent Set >,>=
A={1,2,3}b={1,2}print (a>=b) #判断集合a是否包含集合b的元素, so the result is true
9. Subset <,<=
Print (a<=b) #判断集合a是否被集合b包含, so the result is false
10, go to Heavy
L=[' A ', ' B ', 1, ' A ', ' a ']print (set (L)) #转为集合的形式, the element is displayed once, so the result is {1, ' a ', ' B '}, the result is not in the previous order
11. Circulation
For I in L:print (i)
12, to use the previous method to weight and maintain the order
New=[]for I in L:if I not in new:new.append (i) print (new)
13, using the collection to achieve the weight and maintain order
New=[]s=set () for I in L:if I not in S:s.add (i) new.append (i) print (new)
14. Other uses of the collection
S1={1,2,3}s2={1,2}print (S1-S2) #取得s1和s2的交集, does not change the original set of elements of print (S1.difference (S2)) #取s1和s2不同的地方, does not change the original collection of elements S1.dif Ference_update (S2) #对s1赋值, changed the elements of S1, and the result S1 became {3}print (S2.pop ()) #随机从集合s2中取走一个元素s2. Add (' B ') #给集合s2增加一个元素b S2.discard (' B ') #从集合中删除元素b, delete the element does not exist will not error s2.remove (' B ') #从集合中删除元素b, delete the element does not exist then the error s1={1,2,3,4,5, ' A '}s2={' B ', ' C ',}print (s1.isdisjoint (S2)) #两个集合没有共同部分时, the return value is Trues2.update ({6,7}) #集合s2增加元素6和7, adding multiple elements at once, so the result is {' C ', ' B ', 6, 7}print ( S2)
Seven, character encoding
1, Access files do not garbled the law: with what code to save, what code to read
2, encode and decode
Unicode-----Encode----->GBK
GBK-------->decode----->unicode
3. The character encoding of the Interpreter
The character encoding used by the PYTHON3 interpreter by default is Utf-8
The character encoding used by the PYTHON2 interpreter is ASCII
4.
Python2 's str is Python3 's bytes.
Python2 's Unicode is Python3 str.
Viii. Processing of documents
1, open the file read, the Python process to access the file, the operating system will submit a read request, the operating system to take the data to the process, the process opens up memory space to hold data, so finally to close the file, recycle the operating system resources
F=open (R ' C:\Users\song\Desktop\a.txt ', ' R ', encoding= ' utf-8 ') #最前面的r表示保持字符的本意, otherwise ' \ ' needs to be transferred Data=f.read () print (data) f . Close () #文件关闭, recycle the operating system resource print (F.readline (), end= ") #逐行读, when the file is large, you cannot read all the data at once, you need to read the line
2, in order to avoid forgetting to close the operating system open files, you can directly let the program close
3, write operation, each execution will clear the original data, and then write the new content
F=open (R ' C:\Users\song\Desktop\a.txt ', ' W ', encoding= ' Utf-8 ') f.write (' 11111\n ') f.write (' 1111\n2222\n3333\n ') #写入多 , the end of the line is marked with ' \ n ' f.close ()
Python data types and common methods