I. String
In life we often take the bus, each seat a number, a position corresponding to a subscript. Strings also have subscripts, to take out some of the data in the string, you can use subscripts to take.
- Python usesthin section of specimen for examination (as part of biopsy)nextIntercepts a segment of a stringSliced Interceptsexclusive ofEnd the data corresponding to the subscript.
- Slicing uses syntax:[Start subscript: End subscript: Step] ,pacemakerrefers to the number of subscripts separatinggainOne character.
Note: subscripts will cross the line, slices will not
Common Functions
practice:
Test='rodma ' print(type(Test)) print('A string of %s for Test'%Test[0])# It's like an array # loop output for i in Test: print(i,end=" ")# can also use ' ' print('\n') # count(): count the number of occurrences print(('r')) # join(): loop through all the values and use xx to join them. str='-' print((Test)) # remove both spaces strip(), remove right space: lstrip(), remove right space: rstrip print(()) #copy string, id function looks at the memory address of the object print('Memory address of Test %d'%id(Test)) b=Test # Here it just assigns the memory address of the a object to the b print('Memory address of Test %d'%id(Test)) print(b) # Define a number to be used next with datastr='i love Python' #find function: you can find the target object in the sequence of objects for the value, if you do not find the return -1 print(('M')) # index() function: detects if a string contains substrings Returns a subscript value print(('i')) #Difference between find and index: if index doesn't find the object, it will report an error, find outputs -1, and find outputs 0. #starswith() function: determine the beginning, if so true The #endswith() function is a judgment ending print(('i')) # capitalize(): convert first letter to uppercase # isalnum(): determine whether it is letters and numbers, all are letters on the output of the true, there are spaces can not be # isalpha() :Determine if it is an alpha or not # isdigit(): determine if all are digits # swapcase(): uppercase to lowercase, lowercase to uppercase # title() :make the first letter of each word uppercase # lower(): load to lowercase. # upper(): convert to uppercase a='tsx' print(type(a)) print(()) print(()) print(()) print('abc123'.isdigit()) print(()) print(()) print(()) print(()) # Slice: is to intercept one of the segments of a string. # Slice using syntax: [start subscript: end subscript: step] # The slice intercept does not contain the data corresponding to the end subscript, and the step refers to getting a character every few subscripts. # slice [start:end:step] left closed right open start<=value<end range # Subscripts cross the line, slices don't # # Remember the principle of left closed, right open # Define an object strmgs='Never give up' # Data between 1 and 8 print(strmgs[1:8]) # 3rd character to the end print(strmgs[2:]) # 1st character to 3rd Warm tip: remember left closed, right open print(strmgs[:3]) # What is the step size? For example, if you define 2, it's 2 subscripts from the current one to get a character, or in more general terms, it's every other one to get the next one. print(strmgs[::2]) # Negative direction is output in reverse order, if step size is selected as -1, then output in the opposite direction print(strmgs[::-1]) # Similarly, if the step size is -2, get a character two subscripts away in the opposite direction print(strmgs[::-2]) # There are three total methods + * in # +:Add two objects together, will merge two objects # *:The object itself performs the + operation a specified number of times. # in: determine whether the specified element exists in the object, the output is a bool value strA='I love' strB='Python' print(strA+strB) print(strA*3) print('I' in strA) ''' output <class 'str'> Test a string r r o d m a 1 r-o-d-m-a- - rodma Test's memory address 1863907131504 Test's memory address 1863907131504 rodma -1 0 True <class 'str'> I love python True False False I LOVE pYTHON I Love Python i love python I LOVE PYTHON ever gi ver give up Nev Nvrgv p pu evig reveN p vgrvN I lovePython I loveI loveI love True '''
II. Listings
A list is an ordered collection [] to which elements can be added and removed at any time.
The subscript fetching/slicing/whether or not to cross the boundary of a list is the same as a string, the difference is that a list is fetching elements.
practice
li=[] # Empty list li=[1,2,3,4,'python',True] print(type(li)) The # #len function gets the number of data in the list object. print(len(li)) # append(); appending elements to the list # count(): counts the number of times an element occurs # extend(): extends, which is equivalent to adding bulk # index(): get the index of the specified element # insert(): inserts at the specified position # pop(): removes the next element # remove(): removes the first element found on the left. # reverse(): reverse the list # sort(): list sort reverse=True for reverse order listA=['abcd',785,12.23,'qiuzhi',True] # print('-------------- increased -----------------------') print('Prior to addition',listA) (['fff','ddd']) #Append operation (8888) print('After additions',listA) (1,'This is the data I just inserted') # Insert operation A positional insert needs to be performed print(listA) rsData=list(range(10)) # Force conversion to list objects print(type(rsData)) (rsData) #Expand Equals batch add ([11,22,33,44]) print(listA) # print('----------------- modifies ------------------------') # print('Before modification',listA) # listA[0]=333.6 # print('After modification',listA) listB=list(range(10,50)) print(type(listB)) print('------------ delete list data item ------------------') print(listB) # del listB[0] #delete the first element of the list # del listB[1:3] # batch delete multiple data slice # (20) # Remove the specified element Parameters are specific data values (1) #The parameter is the index value. print(listB) #beg -- Start index, default is 0. #end -- The end index, defaults to the length of the string. print((19)) # Returns an index subscript # Look up, it's a little different than Wonjo, it's open left, closed right # print(type(listA)) print(listA) # Output the complete list print(listA[0]) # Output the first element print(listA[1:3]) # Starting from the second to the third element print(listA[2:]) # All elements from the third to the last print(listA[::-1]) # Negative numbers are output from right to left print(listA*3) # Output data from multiple lists [copy] a=[21,45,66,78] b=[1,2] def add100(x): i= 0 for item in x: x[i]=item+100 i+=1 pass return x pass print(add100(b)) def add100(x): x+=100 return x list2=list(map(add100,a)) print(list2) a=[21,45,66,78] print(list(map(lambda x:x+100,a))) def Old(x): if x>50: return x pass print(list(filter(Old,a))) ''' output <class 'list'> 6 Before appending ['abcd', 785, 12.23, 'qiuzhi', True] After appending ['abcd', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888] ['abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888] <class 'list'> ['abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44] <class 'list'> ------------removinglistdata item------------------ [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] [10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] 8 class 'list'> ['abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44] abcd ['This is the data I just inserted', 785] [785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44] [44, 33, 22, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 8888, ['fff', 'ddd'], True, 'qiuzhi', 12.23, 785, 'This is the data I just inserted', 'abcd'] ['abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 'abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 'abcd', 'This is the data I just inserted', 785, 12.23, 'qiuzhi', True, ['fff', 'ddd'], 8888, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44] [101, 102] [121, 145, 166, 178] [121, 145, 166, 178] [66, 78] '''
III. Tuples
- A tuple is similar to a list, the difference being that the elements of the tuplecannot be modified. Tuple useparentheses ( )The tuple is also accessed via subscripts
- Tuples are easy to create, just add elements in parentheses and separate them with commas.
- Built-in methods for tuples:
count
: count the number of times an element appears in a tupleindex
: Find the subscript index of the specified element in the tuple
practice
# Empty tuple tupleA=() print(type(tupleA)) # Tuples can also be queried with a for statement tupleA=(1,2,3,'cd','a') for item in tupleA: print(item,end=' ') # Tuples can also be sliced, left-closed, right-open. print(tupleA[-2:-1:])# Taking the subscripts in the range of -2 to -1 upside down # # Assuming tuples are put into a queue tupleA=(1,2,3,'cd','a',[11,22,33]) print(tupleA) # The values of the queue can be modified (originally the tuple was not modifiable) print(type(tupleA[5])) tupleA[5][0]=5500 print(tupleA) tupleA[5].append('chen') print(tupleA) ''' output <class 'tuple'> 1 2 3 cd a ('cd',) (1, 2, 3, 'cd', 'a', [11, 22, 33]) <class 'list'> (1, 2, 3, 'cd', 'a', [5500, 22, 33]) (1, 2, 3, 'cd', 'a', [5500, 22, 33, 'chen']) '''
IV. Dictionary
- Dictionary is an important data type in Python that can store arbitrary pairs of images.
- The dictionary is based on thekey-value paircreated in the form of the
{'key':'value'}
Wrap it utilizing curly brackets. - The get method is a safe way to access a value, it can be used when we are not sure if a key exists in the dictionary and we want to get the value, you can also set a default value
Attention:
Dictionary keys cannot be repeated and values can be repeated.
Dictionary keys can only be immutable types such as numbers, strings, and tuples.
Common methods
practice
# Empty dictionary dictA={} print(type(dictA)) # How to add dictionary data? key:value dictA['name']='Chen Yunzhi' dictA['age']=30 print(dictA) # Batch Add dictA={"pro":'Art','shcool':'Beijing Film Academy','age':30,'pos':'xueshen'} print(dictA) # Modify values by keystrokes dictA['pro']='Students' print(dictA) # Add more data ({'name':'Chen Yunzhi'}) print(dictA) # Get all keys and values print((),()) print(()) for key,value in (): print('%s==%s'%(key,value)) # Specify key deletion del dictA['name'] print(dictA) # Sort by key and value print(sorted(())) #print(sorted(())) #Copy, copy, deepcopy copies complex types such as lists and dicts. import copy dictB=(dictA)# Shallow copy dictc=(dictA)# Deep copy print(id(dictc)) print(id(dictA)) print(id(dictB)) dictB['age']='20' dictc['age']='20' print(dictB) print(dictc) print(dictA) print(type(dictB)) print(type(dictc))
Above is the four must know in python advanced data types (character, tuple, list, dictionary) in detail, more information about python data types please pay attention to my other related articles!