Python second week string, list, tuple, collection, dictionary

Source: Internet
Author: User

# string

1. Definition: The type of STR, is a string. Example: var1 = ' Hello world! '

2. Use:

1. Add: +

2. Check: Index (str), find (str), in

common methods of stringsdefMain ():Print(Help ("'. Isalnum)) STR1='Hello, World'    Print(Len (str1))Print(Str1.capitalize ())Print(Str1.upper ())Print(STR1)Print(Str1.find ('o'))#given the occurrence of position I cannot find return-1    Print(Str1.index ('o'))#give the position that appears, can not find the error    Print(Str1.startswith ('He'))#returns True if the check begins with what is not return false.    Print(Str1.endswith ("'))#check what ends with, is return true, not return false    Print(Str1.center (50,'*'))#Center, spare position to fill    Print(Str1.rjust (50,' '))    Print(Str1.ljust (50,'%')) str2='abc123456'    Print(Str2[2])#slices    Print(Str2[2:5])#slices    Print(Str2[-1::-1])#Flashback    Print(str2[2:])#take position 2 to end    Print(Str2[2::2])#take position 2 to end, step is 2    Print(Str2[::2])#from the front to the end, the step is 2    Print(str2[-3:-1])    Print(Str1.isdigit ())#Judging if it's all numbers .    Print(Str2.isalpha ())#Judging if it's all letters .    Print(Str2.isalnum ())#Judging is not all numbers and lettersSTR3 ='[email protected]'    Print(STR3)Print(Str3.strip ())#Remove the space before and after. if __name__=='__main__': Main ()
# list

Defined:

A list is the most basic data structure in Python, and each element in the sequence is assigned a number, its position, or index, the first index is 0, and so on. can be indexed, sliced, increased, reduced, checked. It is implemented by separating square brackets and commas.

Create:

List (), [1, 2, 3, 4], [x for X in range (6)]

# Basic use of the list
defMain (): F= [100, 200, 500] #print (f[0], f[1], f[2]) #For Val in F: #val + = ten #Print (val) #print (f) ## The best way to traverse a container!!!!! It has both subscript and value. #for Index, Val in enumerate (f): #Print (Index, ': ', Val) #crud Operations Create Read Update DeleteF.append (1)#AppendF.insert (1, 1)#Insert #F.remove (500) # knows the value, removes the value from the list, and removes the first value encountered. If not, the error if1inchF:f.remove (1)#above the enhanced version, do not know the value and location #f.clear () # Clear All delF[2]#until the location, delete the element at the specified position directly Print(F.index (100, 0, 5))#know the element and find the position of the element within the specified range. F.pop ()#without the parameters, the last value is deleted by default. Print(f)if __name__=='__main__': Main ()
# Multiple use of the list, matrix.
defMain (): Names= ['Guan Yu','Zhang Fei','Zhao Yun','Ma Chao','Mink Cicada'] Subjects= ['language','Mathematics','Python'] Table= [[0] * LEN (subjects) for_inchRange (len (names))]#Create a matrix of 5 rows and 3 columns. forRow, nameinchEnumerate (names):Print('Please enter the result of%s:'%name) forCol, subjectinchEnumerate (subjects): Score= Int (Input ('%s:'% subject))#Enter values for each locationTable[row][col] = Score#fill in the values for each location Print(table)if __name__=='__main__': Main ()

# tuple tuples

Defined:

Looks like a list, but it is made up of parentheses and commas. As with list, the difference is that the elements inside of him cannot be changed and are better than the list in both time and space. Cannot use or delete operations

defSecond_max (x):#tuple tuples cannot be changed and occupy less space. Secure some, can use tuples, not the list.     """output maximum and second largest value:p Aram x: Input list: return: Returns the maximum and second largest value"""(m1, M2)= (X[0], x[1])ifX[0] > X[1]Else(x[1], x[0]) forIndexinchRange (2, Len (x)):ifX[index] >m1:m2=M1 M1=X[index]elifM1 > X[index] >m2:m2=X[index]returnM1, M2defMain (): My_list= [35, 79, 92, 92, 68, 55, 40]    Print(Second_max (My_list))
# Collection

Defined:

Consisting of curly braces and comma separators, the elements inside cannot be duplicated, duplicates are deleted, and only one value is left, so there is no order, random, unordered, no subscript.

defMain (): Set1= {1, 1, 2, 2, 3, 3} set1.add (4)#Increase    Print(Set1) Set2= {1, 3, 5, 7, 9}    Print(Set2) Set3= Set1.intersection (Set2)#Intersection & Set1 & Set2    Print(set3) Set3= Set1.union (Set2)#The Collection | Set1 | Set2    Print(set3) Set3= Set1.difference (Set2)#difference = minus public part-Set1-set2    Print(set3) Set3= Set1.symmetric_difference (Set2)#symmetry difference = set-intersection ^ Set1 ^ Set2    Print(SET3) forValinchSet2:Print(val)Print(Set2.pop ())#you can get one, there's no guarantee what you got.    Print(Set2)if3inchSet2:set2.remove (3)#Judging, deleting elements    Print(Set2) Set4= {1, 2}    Print(Set4.issubset (Set1))#4 is a subset of 1, Set4 <= Set1    Print(Set1.issuperset (SET4))#1 contains 4. Set1 >= Set4if __name__=='__main__': Main ()
# Dictionary Dict

Defined:

A dictionary is another mutable container model and can store any type of object. Each key value of the dictionary (Key=>value) is split with a colon (:), each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({}) .

defMain (): Dict1= {'name':'Zhang Li',' Age':' the','Jender': True,'motto':'Hello World'}    Print(dict1['name'])    Print(dict1[' Age'])    Print(dict1['Jender']) dict1['name'] ='Wang'  #Update    Print(dict1['name'])    Print(Dict1)#dict1 +={' tell ': ' 123456788 '}Dict1.update (height=174.5, fav=['Eat','Drink'])#add Element    Print(Dict1.pop (' Age'))    Print(Dict1.popitem ())#Delete del    Print(Dict1) forXinchDict1:Print(X,'--->', Dict1[x])#Check    #SetDefault returnDict1.setdefault ('motto','Happy')#originally there, with the original, if not defined, return I define here. if __name__=='__main__': Main ()

  

Python second week string, list, tuple, collection, dictionary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.