1. Common data types
Name = "Jack" #字符串 stringage = 24# integer intheight =1.75# floating-point floatprint (Type (name), type (age), type (height))
2. String and bytes type conversion
msg = "I love Beijing Tian ' an gate" print (Msg.encode (encoding= "Utf-8")) #字符串转bytes类型print (Msg.encode (encoding= "Utf-8"). Decode (encoding = "Utf-8")) #bytes类型转字符串
3. Dictionaries
The dictionary is another mutable container model and can store any type of object. Each key value of the dictionary (key=>value) pairs with a colon (:) split, each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({}) The format is as follows:d = {key1 : VALUE1, KEY2 : VALUE2  The key must be unique, but the value does not have to be. The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple. ' info = { ' stu1101 ': ' Jack ', ' stu1102 ': ' Rose ', ' stu1103 ': ' Marry '}print (info) print (info[' stu1101 ']) info[' stu1101 ']= ' Jack ' #字典修改info [' stu1104 ']= ' Lily ' #字典修改, does not exist add print (info) print (info.get (' stu1105 ')) #获取, there is a return value, there is no return nonedel info[' stu1101 '] #删除info. Pop (' stu1102 ') #删除info. Popitem () #随机删除print (info) print (' stu1106 ' in info ) #判断stu1106是否在info字典里, Returns true on, not returning false# multi-level dictionary nesting and Operation:city = { "Hunan province":{ "Changsha": ["Yuelu District", "Changde"] }, "Chongqing":{ "Fuling": ["mustard", "General"] }, "Beijing": { "Tiananmen": ["Great Wall", "Jinshan"] }}print (city) city["Beijing" ["Tiananmen Square"][0]= "Palace Museum" # Modify the print (city) print (City.values ()) #打印值print (City.keys ()) #打印keycity. SetDefault ("Shanghai", {"Pudong": ["Yangsi", "Oriental Sports Center"]}) #新增, A new City.setdefault ("Chongqing", {"Pudong": ["Yangsi", "Oriental Sports Center"]) print (city) is created with the return of its original value a = { ' stu1101 ': ' Jack ', ' stu1102 ': ' Rose ', ' stu1103 ': ' Marry '}b = { ' stu1101 ': ' Jack ', 1:2, 3:4 }print (a) a.update (b) Print (a) #更新, there is a replacement, there is no new print (A.items ()) #字典转列表c =dict.fromkeys ([6,7,8], ' test ') #初始化一个新的字典, print (c) #字典的循环:d = { ' stu1101 ': ' Jack ', ' stu1102 ': ' Rose ', ' stu1103 ': ' Marry '}for i in d: print (I,d[i]) for j,k in d.items (): print (J,k)
4, string manipulation
name = "My \tname is jack" Print (Name.capitalize ()) #capitalize () method returns a copy of the string, Only its first letter is capitalized. For a 8-bit string, this method is related to the locale. Print (Name.count (' a ')) #count () method is used to count the number of occurrences of a character in a string. The optional parameters are the start and end positions of the string search. Print (Name.center, '-')) #center () Returns the center of the original string and fills the new string with a space of length width . The default padding character is a space of print (Name.encode (encoding= ' utf-8 ')) #encode () method encodes the string in the encoding format specified in encoding . The errors parameter can specify different error handling scenarios. Print (Name.endswith ("CK")) #endswith () method is used to determine whether the string ends with the specified suffix print (name.expandtabs (tabsize=30)) # Expandtabs () method to convert the tab symbol (' \ t ') in the string to a space,tab (' \ t ') The default number of spaces is 8print (name.find (' name ')) # The Find () method detects whether the string contains substrings str , and if beg (start) and end (end) ranges are specified, the check is included in the specified range. Returns 1 if the containing substring returns the starting index value. Print (Name[name.find (' name '): 9]) name = "my name is {name} and {year} old "Print" (Name.format (name= ' Jack ', year=24)) #格式化字符串的函数str. Format () print (Name.format_map ({' name ': ' Jack ', ' Year ': +}) Print (Name.index ('Name ') #查找name的位置print (' as123 '. Isalnum ()) #isalnum () method to detect whether a string consists of letters and numbers, if string There is at least one character and all characters are letters or numbers that return true, otherwise return falseprint (' AsdA '. Isalpha ()) # isalpha () method to detect whether a string consists of only letters. Print (' + '. Isdecimal ()) #isdecimal () method checks whether a string contains only decimal characters; This method exists only in Unicode objects. Note: To define a decimal string, simply add the ' u ' prefix before the string. Str = u "this2009" Print (' 2341 '. IsDigit ()) #isdigit () method detects whether a string is composed only of numbers print (' A1A '. Isidentifier ()) # The judge is not a valid identifier for print (' ASD '. Islower ()) #islower () method to detect whether a string consists of lowercase letters. Print (' 123 '. IsNumeric ()) # isnumeric () method detects whether a string is composed only of numbers print (' '. isspace ()) # Isspace () method detects whether a string is composed only of spaces print (' My name '. Istitle ()) # istitle () method detects whether all the words in the string are spelled in uppercase. And the other letters are lowercase print ('. isprintable ()) #printable : string containing all printable characters print (' DSF '. Isupper ()) #isupper () method to detect whether all letters in a string are uppercase. str = "-";seq = ("a", "B", "C"); # string sequence print (Str.join (seq)) #join () The method is used to generate a new string from the elements in the sequence with the specified character connection. Print (' + '. Join ([' 1 ', ' 2', ' 3 '])) print (Name.ljust (1 ')) # ljust () method returns the original string left-aligned and fills the new string with a space of the specified length. Returns the original string if the specified length is less than the length of the original string. Print (Name.rjust (1 ')) print (' Asasasdf '. Lower ()) #lower () method convert all uppercase characters in a string to lowercase print (' asasasdf '. Upper ()) # Upper () method converts all lowercase characters in a string to uppercase print (' Name is jack '. Lstrip (' name ')) #lstrip () method is used to truncate the space to the left of the string or to specify a character. Print (' name is jack\n '. Rstrip ()) #不填默认去掉右边空格和换行符print (' \nname is jack\n '. Strip ()) #左右都去掉 # Print (". Maketrans ())" Maketrans () method is used to create a conversion table for character mappings, for the simplest invocation method that accepts two parameters, the first argument is a string that represents the character that needs to be converted, The second parameter is also the target of the string representation transformation. Note: The length of the two strings must be the same for the one by one corresponding relationship. "' intab = " Aeiou "outtab = " 12345 "Trantab = str.maketrans (intab, outtab) str = "This is string example....wow!!!" Print (Str.translate (trantab)) print (' my is is is is '. Replace (' is ', ' was ', 3)) #replace () The method replaces the old (old string) in the string with the new (new string), and if you specify a third parameter, Max, the substitution does not exceed max times. Print (' My is is is is '. RFind (' is ')) #rfIND () Returns the position of the last occurrence of the string, or 1 if there is no match. Print (' My is is is is '. Split (' I ')) #split () slices the string by specifying a delimiter, separating only num if the parameter num has a specified value substring print (' ab c\n\nde fg\rkl\r\n '. Splitlines ()) #splitlines () by line (' \ r ', ' \ r \ n ', \n '), returns a list containing the rows as elements, if the argument keepends is false, does not contain a newline character, and if true, the newline character is preserved. Print (' Sadfaasdasdjasas '. Swapcase ()) #swapcase () method is used to convert the uppercase and lowercase letters of a string print (' Jack is '. Title ()) #title () The method returns a "heading" string, meaning that all words start with uppercase and the remaining letters are lowercase (see istitle ()). Print (' This is string example....wow!!! '. Zfill () # zfill () method returns a string of the specified length, the original string is right-aligned, and the front padding is 0.
5, meta-group
Names = (' Jack ', ' Rose ') #与列表类似, except that the elements of the tuple cannot be modified
6. List operation
names = [' Zhangsan ', ' Lisi ', ' Wangwu ', ' Xieliu ', ' Xieliu ']names.append (' Xiaolu ') #追加, default at last Names.insert (1, ' Chenglong ') #插入names. Insert (3, ' Wangli ') #插入names [2]= ' Xiedi ' #修改print (names) print (names[0],names[2]) print (Names[1:3]) #切片, Starting position 1 includes, end position 3 does not include print (Names[-1]) #取列表最后一个值print (names[-2:]) #取最后两个值print (Names.index (' Wangwu ')) #查找wangwu的位置print (Names[names.index (' Wangwu ')]) print (Names.count (' Xieliu ')) #统计xieliu的数量 #names.clear () #清空列表names. Reverse () # Reverse list names.sort () #排序names2 = [1,2,3,4]names.extend (names2) #合并names2到namesnames3 = Names.copy () #复制names到names3, Note: Copy only the first layer (shallow copy) #deletenames. Remove (' Zhangsan ') #删除del names[1] #删除names. Pop () #删除, write subscript default Delete last
7, List copy (shallow copy& deep copy)
import copynames = [' Zhangsan ', ' Lisi ', [' liudeyi ', ' Jack ' ], ' Xieliu ', ' Xieliu ']names2 = names.copy () #复制names到names2, note: Copy only the first layer (light copy) print (names) print (Names2) names[0] = ' Zhang San ' names[2][0] = ' liudeyi ' print (names) print (names2) print ('-------------------- ') names = [' Zhangsan ', ' Lisi ', [' liudeyi ', ' Jack '], ' xieliu ', ' Xieliu '] #names2 = copy.copy ( Names) #浅copy, equivalent to Names2 = names.copy () names2 = copy.deepcopy (names) #深copyprint (names) print ( Names2) names[0] = ' Zhang San ' names[2][0] = ' liudeyi ' print (names) print (names2) print ('------------- -------') #浅copyperson = [' name ', [' saving ', [+]] ' p1 = copy.copy (person) p2 = Person[:]p3 = list (person) "P1 = person[:]p2 = person[:]print (p1) print (p2) p1[0] = ' Jack ' p2[0] = ' Rose ' Print (p1) print (p2) p1[1][1] = 50print (p1) print (p2)
8. List loop
names = [' Zhangsan ', ' Lisi ', [' liudeyi ', ' Jack '], ' xieliu ', ' Xieliu ']print (Names[0:-1:2]) #步长切片, equivalent to print (Names[::2]) For I in Names:print (i)
9. Standard library: OS
Import Os#os, the semantics of the operating system, so it must be operating system-related functions, can handle the files and directories we need to do daily manual operations, such as: Display the current directory of all files/delete a file/Get file size ... #cmd_res = Os.system ("dir") #执行命令, does not save the result cmd_res = Os.popen ("dir"). Read () print ("--", Cmd_res) Os.mkdir ("New dir") #创建目录
10. Simple Shopping Cart Procedure
product_list = [ (' IPhone ', 5800), (' Mac Pro ', 9800 ), (' Bike ', +), (' Watch ', 10600), (' Coffee ', to, (' Alex python ', +)]shopping_list=[]salary = input ("Input your salary: ") if salary.isdigit (): #isdigit () method to detect whether a string consists of only numbers Salary=int (Salary) while true: for index,item in enumerate (product_list): #enumerate functions are used to iterate over the elements in the sequence and their subscripts print (Index,item) user_choice=input ("Choose the item you want to buy >>>:") if User_choice.isdigit (): user_choice=int ( User_choice) if user_choice<len (product_list) and user_choice>=0: p_item=product_list[user_choice] if p_item[1]<=salary: #买得起 shopping_list.append (P_item) salary-=p_item[1] print ("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m "% (p_item[0],salary)) else: print ("\033[41;1m your balance remains [%s], not enough balance \033[0m"% (salary)) else: print ("Product code [%s] is not exist! "% ( user_choice)) elif user_choice== ' Q ': print ('---------shopping list--------') for p in shopping_list: print (P) print ("Your current balance is:", salary) &nbsP; exit () else: #print (' ERROR ') exit ()
Python Learning (day2)