Python Basics-Data types
Python data types include numeric types, strings, lists, tuples, dictionaries, and collections.
1, int integer type
eg:1,2,3 .... Used for calculations, operations.
#.bit_length () The least significant number of digits to convert decimal to binary i = 3i = 4print (I.bit_length ()) "" "Binary decimal 0000 0001 10000 0010 20000 0011 30000 0100 4 "" "
2. STR string
Eg: ' Old boy ', ' Alex ' .... can store a small amount of data
2,1 Index (subscript)
#字符串是有索引的. What is an index? The index is subscript, that is, the elements of the string begin with the first, the initial index is 0, and so on. s = ' python automation operation 21 ' #第一个元素s1 = S[0] #第二个元素print (s1) s2 = s[2]print (s2) #最后一个元素s3 = S[-1]print (s3) #倒数第二个元素s4 = S[-2]print (S4 )
2.2 Slices
#切片就是通过索引 (Index: Index: STEP) intercepts a paragraph of a string, forming a new string (the principle is that Gu head ignores butt). #s [start index: End index + 1: Step] #想要取到第5位s1 = s[0:6] #顾头不顾腚 # 0 can be ignored S1 = S[:6]print (S1) #取6位到8位s2 = s[6:9]print (s2) #开头取到第四位, Interval is one, The step size is 2s3 = S[:5:2]print (s3) #从头取值到结尾s4 = S[:]print (S4) #倒着取到第四个, the step must be written S5 = S[-1:-5:-1] #倒着取值, the reverse step print (S5) must be added
2.3 Operating methods
#对字符串进行操作, form a new string # Common: #全部大写upper () #全部小写lower () s2 = s.upper () s3 = S.lower () print (S2,S3) # # Verify that the password is not case-sensitive code = ' qear '. Upper () Your_code = input (' Please enter a verification code: '). Upper () if Your_code = = Code:print (' verify success ') # Center Center, both sides are filled. The length can be set by itself, the default padding is none s6 = S.center (s6) = S.center ("*") print (S6) #startswith judge with what for the beginning #endswith judge with what for end # is also Gu Tou disregard tail s = ' old Boy ' * * * * startswith ENDSWITHS7 = s.startswith (' o ') s7 = S.startswith (' ol ') s7 = S.startswith (' Oldboy ') s7 = S.startswith (' Bo ', 3,5) print (S7) #后期可以根据开头判断走什么业务逻辑 #strip By default remove the leading and trailing spaces, you can also tab \ t, line break, and also iterate over the element #lstrip () only remove the left #rstrip () only remove the right side of S = ' Oyldboy ' Print (s) #默认去除首尾的空格s8 = S.strip () print (s8) #去除元素s81 = S.strip (' t ') print (s81) #迭代去除元素s81 = S.strip (' Tey ') print ( S81) name = input (' >>> '). Strip () if name = = ' Oldboy ': print (' validation successful ') #split (str---> list) is divided, resulting in a list that does not contain There is this split element # separated by a space or comma S1 = ' Oldboy wusir alex ' s1 = ' oldboy,wusir,alex ' L = s.split () print (l) L = s1.split (', ') print (L) #以o分割, most The final list will have no o element s = ' Oldboywusiroalex ' L2 = s.split (' o ') # [' ', ' ldb ', ' YwusiR ', ' Alex ']print (L2) # can also add the number of modifications L2 = S.split (' o ', 1) # [', ' Ldboywusiroalex ']print (L2) #join will list--->str. Inside the element through the connector to form a new string # Disadvantage: There are non-string elements, will error # S9 = ' + '. Join (s) # S9 = ' _ '. Join (s) # print (S9) # L1 = [' Oldboy ', ' Wusir ', ' alex ']# s91 = ' _ '. Join (L1) # print (s91) #replace Replace, can limit the number of times S = ' big Hammer Fdsalj Hammer sister Edwin van der Sar ' S10 = s.replace (' Hammer ', ' Steel Egg ') print (s10) #find indexed by element No return -1#index found by element index not found error IND = S.find (' d ') print (IND) IND = S.find (' o ') print (IND) IND = s.find (' A ') print (IND) IND = S.index (' A ') print (IND) #公共方法: Tuples, lists, strings can be used in a method #len count how many elements # count elements appear several times s = ' fdsafsdagsdafjdskahdhjlsadhfkj ' Print ( Len (s)) s = ' fdsadd ' Print (S.count (' d ')) #格式化输出formatres = ' I'm {} {} year old, hobby {} '. Format (' Egon ', ', ' Male ') print (res) # can be replaced according to the index res= ' I call {0} this year {1} years old, hobby {2}, I still call {0} '. Format (' Egon ', ' Male ') print (res) #无需注意顺序, can find the value according to key res= ' {name} {age} {sex} '. Format (sex= ' Male ', name= ' Egon ', age=18) print (res) #is系列name = ' jinxin123 ' Print (Name.isalnum ()) # The string consists of letters or numbers print (Name.isalpha ()) #字符串只由字母组成print (Name.isdigit ()) #字符串只由数字组成i = ' 123a ' if I.isdigit (): i = int (i) else:print ("wrong input ...") #不常用: # capitalize uppercase, other lowercase s = ' oldboy ' #capitalize first uppercase, other letters lowercase S1 = S.capitaliz E () print (S1) #* case Reversal swapcase () S4 = S.swapcase () print (S4) #非字母的元素隔开的每个单词首字母大写 title () s = ' Alex Wusir*oldboy3taibia ' S5 = S . Title () # Alex Wusir*oldboy3taibia print (S5)
3, bool Boolean value (True, False)
Converting between #数值 string Boolean #int can be arbitrarily converted to Strint ---> str:str (int) #str转换为int必须全部是数字组成. STR ---> int:int (str) #int convert boolint---> bool 0 False non 0 true#bool to intbool---> int int (Tru e) 1 int (False) 0#str converted to BOOLSTR---> bool "" to False non-empty string is true# print (int (True)) # Print (bool ("")) # False
4, List
eg:[true,1, ' Alex ', {' name ': ' Oldboy '},[1,2,3], (2,3,4), {' Wusir '}]
4.1 list is ordered, indexed value, can be sliced, easy to take value
Li = [111, ' Alex ', 222, ' Wusir ']print (li[1]) # Alexprint (Li[-1]) # wusirprint (Li[:2]) # [111, ' Alex '] Print (Li[:3:2])
4.2 Increase
L = [' Old boy ', ' Alex ', ' Wusir ', ' Taibai ', ' Ritian '] #append in the last append l.append (' gourd ') #无返回值, cannot print Add action l.append ([[+]) print ( L) #insert Insert, any position L.insert (1, ' King Nvshen ') print (L) #迭代着添加, must be iterated and added in by adding the minimum element one by one. L.extend (' Alex ') l.extend ([' 111 ', 222,333]) print (l)
4.3 by deleting
#pop Four operations The only return value is deleted by index print (l.pop (0)) print (l) #remove Delete l.remove (' Alex ') print (l) #clear by element to clear the list, Also occupies a position in memory L.clear () print (L) #del memory level Delete list del lprint (L) #按索引删除del L[1]print (L) #切片删除del L[:3]print (L)
4.4 Change
#按照索引改print (l[2]) l[2] = ' Enrique ' Print (L) #按照切片去改l [: 2] = ' abc ' #切面区域都删除, add by minimum element, can not be peer print (l) l[1:3] = [111,222,333,444] Print (L)
4.5 Check
#按照索引去查询, follow the slice to query for I in L: print (i) L1 = [1,2,1,2,1,1,3,4] #其他方法: Counts the number of elements in #count count print (L1.count (1)) #len Calculate how many elements print (len (L1)) #通过元素找索引, find the first one to return to print (L1.index (2)) L2 = [3,2,4,6,9,8,7,1] #排序 #sort Positive Order L2.sort () from small to large print ( L2) L2.sort (reverse=true) #从大到小排序, add parameter print (L2) #reverse reverse order L2.reverse () print (L2)
4.6 Nesting of Lists
#列表的嵌套l1 = [1, 2, ' Alfdsafex ', ' Wusir ', [' Oldboy ', ' Ritian ', ' ten ', ' Taibai '] #1, turn ' Alex ' all into uppercase and put it back in place. L1[2] = ' ALEX ' #将单独元素赋值 print (L1[2].upper ()) l1[2] = L1[2].upper () print (L1) #2. Add an element ' goddess ' to [' Oldboy ', ' Ritian ', 99]. A method L1[-2].append (' female Fortuna ') print (L1) #3, capitalize the ' Ritian ' first letter and put it back in place. L1[-2][1] = L1[-2][1].capitalize () print (L1) #4, add 10 by number, or string add or so on, into ' l1[-2][-1] = str (l1[-2][-1] + +) print (L1 ) #字符串的拼接l1 [ -2][-1] = str (l1[-2][-1]) + ' 0 ' print (L1)
5. Tuple tuple read-only list
Eg: (true,1, ' Alex ', {' name ': ' Oldboy '},[1,2,3], (2,3,4), {' Wusir '}) read-only list
Store multiple values, tuples are immutable, and more are used to make queries
The tuple itself is immutable, but the inner element can be a mutable type
Tu = (11,2,true,[2,3,4], ' Alex ') #循环去查for i in Tu: print (i) #索引print (tu[1]) #切片print (Tu[:3:2]) #通过元素找索引print ( Tu.index (True)) #元素统计print (Tu.count (2)) print (Len (TU)) #内部的元素可以是可变类型tu [ -2].append (666) print (TU)
6, Dict dictionary key:value in pairs composed of
Eg: {' name ': ' Oldboy ', ' age ': ' name_list ': [' Zhang San ' ...]}
The key to the dictionary is unique. The key must be an immutable data type.
Key: Immutable data type (hash): Str,bool,tuple,int.
Value: Any data type.
Data type classification:
Immutable data type (hash): Str,bool,tuple,int
Variable data type: Dict,list,set.
Container class data type: List,tuple,dict,set.
Dictionary: Store data, relational data, query speed (two-point search).
Before the 3.6 version, the dictionary was unordered, and after 3.6 the dictionary was ordered.
6.1 Increase
#dic [' High '] has the overlay, none adds dic[' High ' = 180dic[' name '] = ' Ritian ' Print (DIC) #dic. SetDefault () has the same, none adds Dic.setdefault (' High ') Dic.setdefault (' High ', Dic.setdefault) (' name ', ' Day of the Day ') print (DIC)
6.2 by deleting
#字典中的key就相当于索引print (Dic.pop (' name ')) # return value corresponding to the value of print (Dic.pop (' name1 ', ' no this key SB ')) #没有name1, delete without error print (DIC) Print (DIC) dic.clear () # Empty print (DIC) print (Dic.popitem ()) #随机删除, return value print (DIC) del Dicprint (dic) del dic[' age ']print (DIC)
6.3 Change
dic[' name ' = ' old boy ' Print (dic) dic = {"Name": "Jin", "Age": "Sex": "male"}dic2 = {"Name": "Alex", "Weight": 75}dic2.update (DIC) # Add the key value of DIC to the Dic2, and DIC will not change. Print (DIC) print (DIC2)
6.4 Check
#get查询, no key does not error print (dic[' name2 ') print (Dic.get (' name ')) print (Dic.get (' name1 ')) print (Dic.get (' name1 '), ' without this key, SB ')) #keys () the conversion of the values () items () Dictionary # converts key to list print (list (Dic.keys ())) for I in Dic.keys (): print (i) # Convert value to list print (Dic.values ()) for I in Dic.values (): print (i) #将键值对放到一个元组, tuples form a list print (List (Dic.items ())) for I in Dic.items (): print (i) #分别赋值a, b = 1,2a,b,c = [' Alex ', ' Wusir ', ' Ritain ']print (a,b,c) A = 1b = 5a,b = B,aprint (A, b) fo R i in Dic.items (): print (i)-k,v in Dic.items (): print (K,V) #len statistics key-value pairs print (len (dic)) #fromkeysdic1 = Dict.fromkeys (' abc ', ' Zhang San ') dic2= Dict.fromkeys ([], ' John Doe ') print (DIC2) #多个都公用一个列表, change one other also change dic3 = Dict.fromkeys (' abc ') , []) # Print (DIC3) dic3[' a '].append (' old boy ') print (DIC3)
6.5 Nesting of dictionaries
DIC = { ' name_list ': [' B ', ' curate ', ' handsome ', ' Kitty '], ' old boy ': { ' name ': ' Old boy ', ' age ': ', ' sex ': ' Ladyboy ', },} #1, [' B ', ' curate ', ' handsome ', ' Kitty '] append an element, ' cavalry ' dic[' name_list '].append (' Cavalry ') print (DIC) #2, to turn kitty into uppercase. L1 = dic[' name_list ']print (L1[-1].upper ()) l1[-1] = L1[-1].upper () print (DIC) dic[' name_list '][-1] = dic[' name_list '][- 1].upper () print (DIC) #3, changing the old boy to Oldboy. dic[' old boy ' [' name '] = ' oldboy ' Print (DIC), capitalize the ladyboy first letter. dic[' old boy ' [' sex '] = dic[' old boy ' [' Sex '].capitalize () print (DIC)
7 Set: Set
Intersection of relational data, set, difference set, subset .... The de-weight of the list.
Collection:
Unordered, non-repeating data type. The elements inside it must be hashed. But the collection itself is non-hashed.
1: Relationship test. Intersection and set, subset, Difference set ....
2, go heavy. (The de-weight of the list)
Set1 = {1, ' Alex ', False, (}L1) = [1,1,2,2,3,3,4,5,6,6]L2 = List (set (L1)) print (L2) Set1 = {' Alex ', ' Wusir ', ' Ritian ', ' Egon ', ' Barry '} #增set1. Add (' 666 ') print (Set1) updateset1.update (' abc ') print (Set1) #删set1 = {' Alex ', ' Wusir ', ' Ritian ', ' Egon ', ' Barry '}set1.remove (' Alex ') # Delete an element print (Set1) set1.pop () # randomly Delete an element print (Set1) set1.clear () # Empty collection print (Set1) del set1 # Delete collection print (Set1)
Set1 = {1,2,3,4,5}set2 = {4,5,6,7,8} #交集 & intersectioprint (Set1 & Set2) print (Set1.intersection (set2)) #并集 | Unionprint (Set1 | set2) print (Set1.union (Set2)) #差集 - differenceprint (set1-set2) print (set1.difference (Set2)) #反交集 ^ symmetric_differenceprint (set1 ^ set2) print (Set1.symmetric_difference (Set2)) # {1, 2, 3, 6, 7, 8}set1 = {-) Set2 = {1,2,3,4,5,6} #子集与超集print (Set1 < Set2) print (Set1.issubset (Set2)) # These two are the same, both of which indicate that Set1 is a subset of Set2. Print (Set2 > Set1) print (Set2.issuperset (Set1)) #不可变几个, let the collection become immutable s = Frozenset (' barry ') S1 = Frozenset ({4,5,6,7,8}) Print (S,type (s)) print (S1,type (S1))
8, the Data type supplement
L1 = [' Alex ', ' Wusir ', ' Taibai ', ' Barry ', ' old boy '] #删除奇数为元素, slice del l1[1::2]print (L1) #再循环一个列表时, do not delete the list of actions (change the number of elements in the list action), Error for I in range (len (L1)): print (L1) # [' Alex ', ' Wusir ', ' Taibai ', ' Barry ', ' old boy '] # [' Alex ', ' Wusir ', ' Taibai ', ' Barry ', ' old boy '] # [' Alex ', ' Taibai ', ' Barry ', ' old boy '] # [' Alex ', ' Taibai ', ' Barry ', ' old boy '] print (i) # 0 1 2 3 if I% 2 = = 1:del L1[i] Print (L1) # [' Alex ', ' Wusir ', ' Taibai ', ' Barry ', ' Old boy '] # [' Alex ', ' Taibai ', ' Barry ', ' old boy '] # [' Alex ', ' Taibai ', ' Barry '] Print (i) # 0 1#range Customizable A list of numbers, Gu Tou disregard tail range customizable list of numbers for I in range: print (i) for I in Range (1,10): Print (i) #设置步长for I in Range (1,10,2): P Rint (i) #倒序for I in Range (10,1,-1): print (i) print (range) for I in range (len (L1) -1,-1,-1): If I% 2 = = 1:de L L1[i]print (L1) dict re-cycle the dictionary, do not change the size of the dictionary. DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 ', ' r ': 666}l1 = []for i in dic:if ' K ' in I:l1.append (i) # print (L1) foR i in L1:del dic[i]print (dic) Tu if there is only one element in the tuple and no comma is separated, then his data type is consistent with that element. TU1 = (1) print (Tu1,type (TU1)) TU2 = (' Alex ') print (Tu2,type (TU2)) Tu3 = ([' Alex ', Up]) print (Tu3,type (TU3))
9. Homework (Shopping cart)
Python basic "Data type"