1.1 Data Types
Common data types in python: strings, integers, floating-point numbers, lists, dictionaries, Boolean values, and tuples.
There are three basic data types:
String str: text enclosed in parentheses (eg: 'python', '123', 'wind-variable programming')
Integer int: a number without a decimal point (eg: -1, 1, 0, 520, 1314)
Floating-point number float: a number with a decimal point, the operation result has an error (such as: -0.15, 3.1415, 1.0)
The following data structures will be introduced in a course or two, so you can easily get started.
list list : It is an ordered collection in which elements can be added or deleted at any time. Identifiers are square brackets [].
tuple: A data type similar to a list, but cannot be modified. Identifiers are parentheses ().
The element values in the tuple are not allowed to be modified, but we can connect and combine the tuples, as shown in the following example:
tup1=(12,34.56) tup2=('abc','xyz') tup3=tup1+tup2 print(tup3) #Then the print result is (12,34.56,'abc','xyz')
Dictionary dic: The full name is dictionary, which uses key-value pairs (key-value) as a storage method. Identifiers are braces {}. Boolean value bool: A data type that represents true and false, with only two values, True and False.
1.2 Data operation
1.2.1 String concatenation
1.2.1.1 Using '+'
Primary usage: use '+' to concatenate strings
print('wind change'+'programming') wind change programming name='sauce' begin='My name is' print(begin+name) my name is sauce
1.2.1.2 Using '%'
Advanced usage: use '%' to concatenate strings
name='<"Phoenix Seeking Phoenix"' 2>>>number=1 3>>>print('Sima Xiangru%d song%s impressed Zhuo Wenjun'%(number,name)) 4 Sima Xiangru moved Zhuo Wenjun with a song "Phoenix Seeking the Phoenix" %format: str%() print('%s%d'%('number:',0)) print('%d,%d'%(0,1)) print('%d,%d,%d'%(0,1,0)) name1='Python' print('Iamlearning%s'%name1) #Note: When there is only one data, there is no need to add parentheses after %, and format() must have a=2.33333 print('a Values with one decimal place:%.1f'%a) print('a Values with two decimal places:%.2f'%a)
1.2.1.3 format usage
#format() formatting function: str.format() print('\n{}{}'.format('number:',0)) #Advantage 1: Don't worry about using the wrong type code. print('{},{}'.format(0,1)) #When the specified position is not set, it corresponds to the order by default. print('{1},{0}'.format(''a'',''b'')) #Advantage 2: When setting the specified position, press the specified corresponding. print('{0},{1},{0}'.format(5,6)) #Advantage 3: The format ted data can be called multiple times. name2='Python basic grammar' print('i'm learning{}'.format(name2)) #The format() function also accepts incoming data via parameters
1.2.2 String segmentation
str.spilt() #Returns a list of the words in the string 1>>>'1,2,3'.split() 2['1',',','2',',','3'] 3>>>'1,2,3'.split(',') ['1','2','3']
1.2.3 Remove the spaces in the string
1.strip(): remove the leading and trailing spaces
2.lstrip(): remove the space on the left
3.rstrip(): remove the space on the right
4.replace('c1','c2'): Replace c1 in the string with c2. So you can use replace(' ','') to remove all spaces in the string
5.split(): Slice the string by specifying the delimiter, if the parameter num has a specified value, only num substrings will be separated
In[2]: a=' ddd dfe dfd efre ddd ' In[3]: a Out[3]: ' ddd dfe dfd efre ddd ' In[4]: a.strip() Out[4]: 'ddd dfe dfd efre ddd' In[5]: a.lstrip() Out[5]: 'ddd dfe dfd efre ddd ' In[6]: a.rstrip() Out[6]: ' ddd dfe dfd efre ddd' In[7]: a.replace(' ','') Out[7]: 'ddddfedfdefreddd' In[8]: a.split() Out[8]: ['ddd', 'dfe', 'dfd', 'efre', 'ddd'] In[3]: a = 'dfdfd*dfjdf**fdjfd*22*' In[4]: a Out[4]: 'dfdfd*dfjdf**fdjfd*22*' In[5]: a.split('*') Out[5]: ['dfdfd', 'dfjdf', '', 'fdjfd', '22', ''] In[6]: a.split('*',2) Out[6]: ['dfdfd', 'dfjdf', '*fdjfd*22*']
6. Use regular expressions
>>> re.split(r'\s+', 'a b c') ['a', 'b', 'c']
1.2.4 Four arithmetic operations
operator | express | example |
+ | add | 1+1 output result is 2 |
- | reduce | 1-1 output result is 0 |
* | take | 3*2 output result is 6 |
/ | remove | 2/1 outputs 2 |
% | modulo - returns the remainder of the division | 5%2 output result is 1 |
** | power - returns x raised to the power of y | 2**3 output result is 8 |
// | Round and divide - returns the integer part of the quotient | 11//2 output result is 5 |
Operation priority: Same as normal operation priority: from left to right, the calculation in parentheses takes precedence, and multiplication and division come before addition and subtraction.
1.2.5 Data type conversion
1.2.5.1 type()
#Check the data type of a variable 1>>>who='xiaojiangjiang' 2>>>print(type(who)) 3<class'str'> 4 5#The result shows that this is a string type of data
1.2.5.2 str()
#Cast other data types to strings 1>>>begin='I ate' 2>>>number=1 3>>>fruit='fruit' 4>>>print(begin+str(number)+fruit) 5 I ate 1 piece of fruit 6#When concatenating strings, different data types cannot be connected directly using '+', you need to convert the integer to a string type now
1.2.5.3 int()
#Convert a string in the form of an integer to an integer (a text string and a string in floating point form cannot be converted to an integer) #Direct zeroing and rounding of floating point numbers 1>>>print(int(3.8)) 23
1.2.5.4 float()
#Convert integers and strings to floating point numbers (literal strings cannot be converted) 1>>>print(float(8)) 28.0
1.2.5.5 list()
#Convert data to list type 1>>>a='python small class' 2>>>print(list(a)) 3['p','y','t','h','o','n','Small','class']
1.2.5.6 len()
#Used to check the length of a certain data 1>>>bros=['Liu Bei','Guan Yu','Zhang Fei'] 2>>>print(len(bros)) 33 4>>>emotion='happy' 5>>>print(len(emotion)) 65
1.3 Common syntax for data
1.3.1 List Syntax
List operations can be divided into two types, one type is the processing of list elements, the other type is the processing of lists, each type has four operations: extract, modify, add, delete (take, change, add, delete ).
Offset: The position number for the list element.
#List offsets start at 0 #If you want to extract a list, you need to use the slice form [a:b]: elements from a to b, but not including b (a<=X< b);If there is no number on one side of the colon, take all 1>>>list=['loose','bamboo','plum'] 2>>>print(list[0]) 3>>>print(list[1:2]) 4>>>print(list[:2]) 5 loose 6['bamboo'] 7['loose','bamboo'] 8#The offsets of pine, bamboo, and plum are 0, 1, and 2 respectively.
1.3.1.1 Extraction of list elements
1>>>list=['loose','bamboo','plum'] 2>>>print(list[0]) 3 loose 4 5>>>list=[['loose','pine'],['bamboo','bamboo'],['plum','plum bossom']] 6>>>print(list[0][1]) 7 pine 8#Extraction of nested lists
1.3.1.2 Modification of list elements
1>>>list=['loose','bamboo','plum'] 2>>>list[0]='pine' 3>>>print(list) 4['pine','bamboo','plum']
1.3.1.3 Addition of list elements
1.3.1.3.1 append()
#is a list method, add an element within the brackets, you can add the element to the end of the list 1>>>list=['loose','bamboo'] 2>>>list.append('plum') 3>>>print(list) 4['loose','bamboo','plum'] Mistake one: use append cannot assign a value to a list when 1>>>list=['loose','bamboo'] 2>>>list=list.append('plum') 3>>>print(list) 4None 5#syntax error on second line Mistake 2: append followed by parentheses, not square brackets 1>>>list=['loose','bamboo'] 2>>>list.append['plum'] 3>>>print(list) 4TypeError:'builtin_function_or_method'objectisnotsubscriptable 5#syntax error on second line Mistake three: append Cannot add multiple elements at once 1>>>list=['loose','bamboo'] 2>>>list.append('plum','Three Friends of Winter') 3>>>print(list) 4TypeError:append()takesexactlyoneargument(2given) 5#syntax error on second line
1.3.1.3.3 extend() function
d=[4,5,6] c=[1,2,3] d.extend(c) print(d) #The output is: [4,5,6,1,2,3] 1.3.1.3.4 insert() list.insert(index, obj) #index -- The index position where the object obj needs to be inserted. #obj – the object to insert into the list. example aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print "Final List : ", aList #output Final List : [123, 'xyz', 'zara', 2009, 'abc']
1.3.1.4 Deletion of list elements
1.3.1.4.1 del
#delete command Mistake 1: Only one element can be deleted at a time. Mistake 2: When deleting multiple elements, the offset must be recalculated 1>>>list=['loose','bamboo','plum'] 2>>>del list[0] 3>>>print(list) 4>>>dellist[0] 5>>>print(list) 6['bamboo','plum'] 7['plum'] 1.3.1.4.2 pop 1#extract and delete 2students=['Xiao Ming','little red','Xiaogang'] 3for i in range(3): 4student1=students.pop(0)#Use the pop() function to complete extraction and deletion at the same time. 5students.append(student1)#Arrange the removed student1 to the last seat. 6print(students) 1.3.1.4.3 remove #delete the specified element sandwich_orders=['veggie','grilledcheese','turkey','roastbeef','pastrami','pastrami','pastrami'] finished_sandwiches=[] print("I'msorry,we'realloutofpastramitoday.") while'pastrami'insandwich_orders: sandwich_orders.remove('pastrami')#remove all 'pastrami' print(sandwich_orders)
1.3.1.5 List slicing (extraction)
(That is, extraction at the list level, extracting several elements at a time)
list2=[5,6,7,8,9] print(list2[:]) #The output result is [5,6,7,8,9], the colon: means to take all print(list2[2:]) #Here it is counted from the offset of 2 (taken from the left), so the corresponding output is [7,8,9], the colon: means to take all the following print(list2[:2]) #Here is the offset to 2 (the right is not taken), so the corresponding output is [5,6], colon: means to take all the previous print(list2[1:3]) #Here the corresponding is from offset 1 (left take) to offset 3 (right not taken), so the output corresponds to [6,7] print(list2[2:4]) #This corresponds to offset 2 (left take) to offset 4 (right not taken), so the output corresponds to [7,8] #Note: The slice of the list extracts the list
1.3.1.6 List modification (assignment)
#Also use the assignment statement, pay attention to the assignment to the list 1>>>list=['loose','bamboo','plum'] 2>>>list[:]=['Three Friends of Winter'] 3#list[:] means to take out all the elements of the list 4>>>print(list) 5['Three Friends of Winter'] 6 7#Watch out for the following wrong practices: 8>>>list=['loose','bamboo','plum'] 9>>>list[:]='Three Friends of Winter' 10>>>print(list) 11['age','cold','three','friend']
1.3.1.7 List addition (merging)
It would be more reasonable to call the addition of a list a merge of lists
1.3.1.7.1 #Use the symbol '+'
#The symbol '+' can only be used between lists, not between lists and elements
1>>>list1=['loose'] 2>>>list2=['bamboo'] 3>>>list3=['plum'] 4>>>list=list1+list2+list3 5>>>print(list) 6['loose','bamboo','plum']
1.3.1.9 List deletion
1.3.1.9.1 del
#delete command
1>>>list=['loose','bamboo','plum'] 2>>>dellist[:2] 3>>>print(list) 4['plum']
1.3.1.10 List Comprehensions
names=['Eric','Lily','Polly','Admin','Jack'] new_names=['Lilei','Lily','Hanmeimei','John','Jack'] names_lower=[i.lower()foriinnames]#Convert all characters in names to lowercase foriinnew_names: ifi.lower()innames_lower: print('Sorry,{}istaken'.format(i)) else: print('Good,youcanuse{}'.format(i))
#List comprehension method 2 current_users_lower=[] foruserincurrent_users: current_users_lower.append(user.lower())
1.3.1.11 Multiplication of 2 lists
for i,j in zip(list1,list2): a=i*j list_result.append(a)
1.3.1.12 List related functions
1.3.1.12.1 sort and sorted function sorting
The difference is that sort is permanent and sorted is temporary
sort() function (permanently changes the ordering of elements of a list)
Usage: ListName.sort()
a=[2,3,1,4,3] a.sort() print(a) a.sort(reverse=True)#reverse order print(a) #The result is [1,2,3,3,4] [1,2,3,3,4] [4,3,3,2,1]
sorted() function (temporarily sort the list temporarily)
Usage: sorted( list name)
a=[2,3,1,4,3] print(sorted(a)) print(sorted(a,reverse=True))#reverse order print(a) #The results were [1,2,3,3,4] [4,3,3,2,1] [2,3,1,4,3]
1.3.2 Dictionary Syntax
1.3.2.1 Extraction of dictionary data
1.3.2.1.1 Single element extraction
# Lists are extracted using offsets, dictionaries are extracted using keys
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>print(group['master']) 3 Tang Sanzang
1.3.2.1.2 Extract all the keys in the dictionary
dict.keys()
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>print(group.keys()) 3dict_keys(['master','big brother','Second Senior Brother','Brother Sha']) 4#Print out the keys of all dictionaries, but in the form of tuples 5 6>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 7>>>print(list(group.keys())) 8['master','big brother','Second Senior Brother','Brother Sha'] 9#Use the list() function to convert the tuple into a list form
1.3.2.1.4 Extract all the values in the dictionary
dict.values()
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>print(group.values()) 3dict_values(['Tang Sanzang','sun walker','Zhu Bajie','sand monk'])
1.3.2.1.5 Extract all key-value pairs in the dictionary
dict.items()
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>print(group.items() 3dict_items([('master','Tang Sanzang'),('big brother','sun walker'),('Second Senior Brother','Zhu Bajie'),('Brother Sha','sand monk')])
1.3.2.1.6 Method 2 for extracting keys and values
A={'green':1,'red':2,'yellow':3} forkey,valueinA.items(): #print(key) #output green, red, yellow print(value) #output 1,2,3
dictionary use keys(method): dictionary extract key A={'green':1,'red':2,'yellow':3} forkeyinA.keys(): #print(key) #output green, red, yellow
#Dictionaries use the values method: Dictionaries extract values A={'green':1,'red':2,'yellow':3} forvalueinA.values(): print(value) #output 1,2,3
1.3.2.2 Modification of dictionary data
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>group['master']='Tang Xuanzang' 3>>>print(group) 4{'master':'Tang Xuanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'}
1.3.2.3 Increase of dictionary data
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>group['white dragon horse']='Ao Lie' 3>>>print(group) 4{'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk', 'white dragon horse':'Ao Lie'}
1.3.2.4 Delete dictionary data
1>>>group={'master':'Tang Sanzang','big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'} 2>>>delgroup['master'] 3>>>print(group) 4{'big brother':'sun walker','Second Senior Brother':'Zhu Bajie','Brother Sha':'sand monk'}
1.3.3 Expressions yielding Boolean values
1.3.3.1 bool()
# check the value is true or false
1>>>print(bool(1))
2True
the value itself as the condition
Fake | everything else is true |
False | True |
0 | 5 (any integer) 1.0 (any float) |
'' (empty string) | 'wind-variant-programming' (string) |
[] (empty list) | [1,2,3] |
{} (empty dictionary) | {1:'a',2:'b'} |
None |
Comparison operators produce boolean values
operator | paraphrase | effect |
== | equal | If the values on both sides are equal, the condition is true |
!= | not equal to | If the values on both sides are not equal, the condition is true |
> | greater than | The condition is true if the value on the left is greater than the value on the right |
< | less than | The condition is true if the value on the left is greater than the value on the right |
>= | greater than or equal to | The condition is true if the value on the left is greater than or equal to the value on the right |
<= | less than or equal to | The condition is true if the value on the left is less than or equal to the value on the right |
Note: Do not use spaces between operators, and cannot be written as ==, >= |
Membership operators produce boolean values
operator | paraphrase | effect |
in | belong | The condition is true if the value is in the specified sequence |
notin | Does not belong | The condition is true if the value is not in the specified sequence |
Logical Operators produces a boolean value
operator | paraphrase | effect |
and | and | Concatenates two boolean values, the condition is only true if both are true |
or | or | Concatenates two boolean values, if one is true, the condition is true |
not | non |