1, Data type
All data in the computer can be regarded as objects, and variables play the role of pointing to data objects in the program.
The data types commonly used in python are divided into basic data types (number, str) and composite data types (list, tuple, dict, set)
Basic data type
1.number (numeric)
int
float (no double)
complex
bool
be careful:
1.bool type has only two values: True and False (initial capital). Because bool inherits int type, True is equivalent to 1 and False is equivalent to 0. Bool type variables can participate in mathematical operations
2. Non-0 numeric variable, non empty string is True, and True can be obtained by data type conversion with bool()
2.str (string)
The Unicode character sequence is stored, and any character is enclosed in quotation marks, which can be single quotation marks or double quotation marks
be careful:
1. If there is an apostrophe in the string enclosed in single quotation marks, an error will occur. python will treat the content between the first single quotation mark and the apostrophe as a string.
2. The string supports indexing. The indexing method is the same as that of the list. Refer to the following list and also supports slicing, as shown below.
3.python does not have a separate character type, but the char type in C
#Nearest matching "'...'" # √ '"..."' # √ ""..."" #× ''...'' #×
Operation:
s1+s2 #Use + to splice strings ''' Modify the string size. Note that only the returned string size changes ''' s.title() #Display each word in uppercase, that is, change the first letter of each word to uppercase. s.upper() #Returns a pure uppercase string s.lower() #Returns a pure lowercase string s.swapcase() #Returns a case flipped string s.capitalize() #Capitalize the first character of the string (if the first character is a letter) ''' Delete the blank. Note that it is not permanently deleted. You need to store the result in a variable Blank: generally refers to any non printed character, eg Spaces, tabs\t,Newline character\n ''' s.rstrip() #Delete the blank at the end s.lstrip() #Delete the beginning blank s.strip() #Remove both beginning and end whitespace s.find(subs) #Find out whether the specified content sub exists in the string s. if so, return the index value of the content appearing in the string for the first time. Otherwise, return - 1 s.rfind(subs) #And find types, but they are retrieved from the end s.startwith(subs) #Judge whether the string starts with sub. if yes, it returns True; otherwise, it returns False s.endwith(subs) #. . . ending s.count(subs) #Returns the number of occurrences of subs s.replace(Old string, new string) #Replace the old string with the new string. If the number of times is specified, the number of replacements will not exceed the specified number """ Other methods """ len(s) #Get length s.split(parameter) #Cut the string through the parameter content and return the list s.splitlines() #Separated by line, returns a list. One element of the list is the string content of one line s.encode(parameter) #Encode in the specified encoding format s.decode(parameter) #Decode in the specified encoding format
Composite data type
Container in computer language refers to the collection of data elements formed by combining data elements in some way, that is, data types. Containers that can hold multiple types of elements are called composite data types. python containers contain sequences, maps, and collections.
Sequences include: str, list, tuple, buffer objects, etc
Unique mapping type: dict
Set: set (mutable set), frozenset (immutable set)
1.list
The list is represented by []. The list is an ordered sequence containing several object references. All data elements of the list are object references, so variables of data types can be stored.
List has index - list name [index]. The index starts from 0. For convenience, Python provides a special syntax. By specifying the index as - 1, Python can return the last element of the list, and - 2 returns the penultimate element
Note: do not cross the boundary when using the list index. When the list is empty, an error will appear in list[-1]
Operation:
list--Create, add, delete, modify, query, others establish: ''' 1.Can be directly through[]Create, empty[]Represents an empty list, and multiple data elements are separated by commas 2.list()For function creation, the maximum number of function parameters is one. When no parameters are given, an empty list is returned. When parameters are taken, a shallow copy of the adopted number is returned ''' list=[] Add: list.append(v) #Add element v at the end of the list insert(i,v) #Insert v before the element with index i, that is, v becomes the element with index i list1.extend(list2) #Add the elements of list2 to list1 one by one Change: list[i]=v #Change the value with index i to v check: list[i] #Indexes list.index(v) #Returns v the location index that appears for the first time. If it does not exist, an error will be reported list.count(v) #Count the number of times v appears in the list #in,not in if v in list: #Returns True if it exists, otherwise returns false print("existence") if v not in list: #If there is no, return True, otherwise return false print("non-existent") Delete: del list[i] #Delete element with index i list.pop() #Deletes the last element and returns the value of the element list.remove(v) #Delete the element with value v. if there are multiple elements, delete the first one len(list) #Learn the length of the list ''' Organization list ''' list.sort() #Sort the list from small to large, list.sort(reverse=True) #Order from large to small sorted(list) #Temporarily sort the list, that is, the list order is actually unchanged, and only the sorted list is returned #To reverse the order, pass the parameter reverse=True to sorted() list.reverse() #Reverse the list
2.tuple
The list is very suitable for storing data sets that may change during operation. The list can be modified. But sometimes we need to create a series of immutable elements, and tuples can meet this requirement.
Tuples are defined by parentheses (). Elements can be accessed by index, traversable, and cannot be modified. Only the direction of tuple variables can be modified.
#If there is only one tuple element, you need to add a comma after the element print(type((1))) #Type returns the type of data print(type((1,))) #Output: <class 'int'> <class 'tuple'>
section
————Intercepting a part of the operation object.
String, list and tuple can be sliced
#Take list as an example #Create slice list[m,n,r] #Returns the list intercepted in steps of r from index m to index n (not included). If r is omitted, it is 1 [m:] #Returns the content from the index m to the end [:,n] #Returns content that contains from index 0 to n (not included) #Traversing slices -- same as traversing lists #Copy list - creates a slice that contains the entire list list_new=list[:] list_new=list #Invalid, list_new and new point to the same list
6.dict (Dictionary)
A dictionary is a series of key value pairs enclosed by {}, in which each key is associated with a value,
Keys and values are separated by colons, and key value pairs are separated by commas.
be careful:
1. The keys are not allowed to be the same, but can only be the same
2. The value of the same key is modified several times, and the last one shall prevail, that is, overwrite processing
3. Keys are object references to immutable objects (such as number, str, tuple), and values are object references to objects of any type
Explanation of immutable objects:
Immutable object means that the state of an object cannot be changed after it is created
#Take str as an example, number is similar, and tuple itself cannot be modified s1='fksla' s2=s1 print(s2 is s1) #At this time, the s1 and s2 object references point to the same object and the same memory space print(id(s1),id(s2)) #id() returns the address of the object pointed to s1=s1+'s' #This s1 is no longer the previous s1. It does not mean that the value of the object it originally pointed to has changed, but that a new memory has been opened up in memory to store the new value, and s1 is the object reference of the new object, which is the same as the string in java print(s2 is s1) print(id(s1),id(s2)) #output # True # 2623639886384 2623639886384 # False # 2623639834736 2623639886384 #Like list, dict is a variable object. Take list as an example l1=[1,2,'ds'] l2=l1 print(l1 is l2) print(id(l1),id(l2)) l1.append(2) print(l1 is l2) print(id(l1),id(l2)) #output # # True # 2926545055104 2926545055104 # True # 2926545055104 2926545055104
operation
dict--Create, add, delete, modify and query establish: and list Type. When the function is created, the parameters are mapping type parameters Check: dict[key] #Returns value. If it does not exist, an exception occurs dict.get(key) #Return value. If it does not exist, no exception will occur, and return None if k in dict: #Returns v if k exists print(dict[k]) if k not in dict: #If it doesn't exist, add one dict[k]=v #Modify not add Change: dict[k]=v Add: dict[k]=v #Nonexistent k Delete: del dict[k] del dict #The whole dictionary has been deleted. The dictionary object does not exist dict.pop(k) #Deletes the specified key value pair dict.clear() #Empty the dictionary and become an empty dictionary {}
nesting
#Dictionary list. Each element of the list is a dictionary [{},{},{},....] #The list is stored in the dictionary. When a key has multiple values, it can be stored in the list. The values need to be traversed {key:[],....} #Store dictionary in dictionary {key:{},....}
2, Data type conversion
View variable data type (variable name)
After assigning a value to a variable, the object it points to is created and memory space is allocated in memory. The function type() can judge the type of the object. Data type conversion may be carried out between different types, as shown below.
a=12 print(type(a)) a=2.3 print(type(a)) a='sad' print(type(a)) #Output: <class 'int'> <class 'float'> <class 'str'>
a. Convert to integer
int(x)
x is a string, and the string content is a numeric value (and not a floating-point value) '1.23' cannot be converted
If x is a floating point number, the integer part is returned
x is a boolean type, True returns 1, and False returns 0
b. Convert to floating point number
float(x)
The string x content is numeric
c. Convert to string
str(x)
d. Convert to boolean type
bool(x)
x is numeric data, non-0 returns True, and 0 returns False
x is a string. When the string is not empty, it returns True; otherwise, it returns False
x is a list, tuple and dictionary. It returns True as long as it is not empty, otherwise it returns False
#Is False: bool(0) bool(0.0) bool('') bool("") bool(()) bool([]) bool({})
3, Variable naming convention
– can only contain letters, numbers and underscores. And start with a letter or underline
– Python keywords (reserved words) and function names cannot be used as variable names
– follow short + descriptive (see the meaning of the name)
– use lowercase l and uppercase O with caution
– variable name lowercase