Weekly Summary - week02
Basic data types and their built-in methods
1, the basic data type of integer (int)
Overview:
Integer ( int): Integer refers to all kinds of integers. Integer is an immutable data type. Grammatical structures: variable name = integer value eg: age = 18
Built-in method:
Integer type conversion
grammar: int() pass int(other data types)Other types of data types can be converted to integer types. eg: string_demo = '138158168188198' int(string_demo)
decimal number conversion
Python When performing numerical conversion, because of its low precision, if you need to perform accurate calculations, you need to borrow modules—— numpy Syntax: Convert decimal to other bases bin() binary oct() Octal hex() hex Syntax: Convert other bases to decimal int(0b) binary to decimal int(0o) Octal to Decimal int(ox) Hexadecimal to decimal eg: Convert decimal to other bases num = 368 rs = bin(num) binary print(rs) oct(num) Octal rs1 = oct(num) print(rs1) hex(num) hex rs2 = hex(num) print(rs2) Convert other bases to decimal int(0b101110000) binary to decimal int(0o560) Octal number to decimal int(0x170) Hexadecimal to decimal
2, the basic data type of floating point (float)
Overview:
float ( float): is a decimal Grammatical structures: variable name = decimal
Built-in method:
Type conversion: float(other data types) eg: string_demo = '13.14' # only one decimal point float(string_demo)
3. String (str) of the basic data type
Overview:
string ( float): It consists of single or multiple characters and is written in single, double, triple, and triple double quotation marks. The reason for so many quotes is to prevent conflicts Grammatical structures: variable name = 'character or string'(Any of the above four quotation marks can be used) eg: teacher_speak = 'Northland scenery, thousands of miles of ice, thousands of miles of snow'
Built-in method:
index value
''' The starting position of the index value is 0, and an error will be reported directly if it exceeds the range. variable name[subscript] ''' str1 = '8567.189.FBI' str1[0] print(str1[0], type(str1)) # The value with subscript -1 is the last character of the string print(str1[-1])
Slicing operations and changing the orientation of slices
''' variable name[ : : ] #The first number is the starting position, the second is the ending position, and the third is the step size ''' str1 = '8567.189.FBI' # Start cutting from the position where the subscript is 0, (in fact, the initial position is 0 by default), you can not write # Cut until the data value with the subscript 4 in front of the data value with the subscript 5, only cut before the subscript 5 # 2 means the step size, take one every other rs = str1[0:5:2] # The output result is the original string, we can know that the string is an immutable data type print(str1) # If you take the variable name after the assignment, you can output 86. print(rs) ''' By default, the slice operation takes values from left to right. If you want to change the direction, you need to set the step size to-1. You cannot get from a negative number to a positive number (you can get to 0). ''' str1 = '8567.189.FBI' # The step size is set to -1 to obtain rs = str1[-1:-5:-1] print(rs) # If no value is written before or after the colon, all values are required by default. rs = str1[:] print(rs) # If you do not write before the first colon, the default value is 0 rs = str1[:5] print(rs) # If you do not write after the first colon, it defaults to the total length of the string #The default value of the step size is 1, which means that each print(str1[:5:])
count the number of characters in a string
# String length acquisition method len() print(len(str1))
Remove the specified characters from the beginning and end of a string
''' .strip() The characters at the beginning and end of the string can be removed, and can be specified. If not specified, the default is to remove the spaces at the beginning and end. If specified, the corresponding characters can be removed, or the left side can be specified. lstrip(),Or specify to remove the right rstrip(). ''' # Remove all spaces before and after str1 = ' 8567.189.FBI ' print(str1.strip()) # Remove all $ signs before and after str2 = '$$$8567.189.FBI$$$' print(str2.strip('$')) # Delete the first and last 12 strings str2 = '123.8567.189.FBI.321' print(str2.strip('12')) # remove the left string str3 = '$$$8567.189.FBI$$$' print(str3.lstrip('$')) # remove the right string str3 = '$$$8567.189.FBI$$$' print(str3.rstrip('$'))
Cuts the specified character in a string
''' split()The method can cut a string type data into a list by the specified character ''' str1 = 'name|age|addr' str1.split('|') # Decompress and assign the variable str1 to the three variables sex, name, and age by identifying '|' str1 = 'man|Jason|eleven' sex, name, age = str1.split('|') print(age, type(age)) # Cut the specified number from left to right split() The default is to cut from the left str1 = 'name|sex|addr|age|hobby' rs = str1.split('|', maxsplit=2) print(rs) # Cut the specified number from right to left maxsplit=1 means the maximum number of cuts str1 = 'name|sex|addr|age|hobby' rs = str1.rsplit('|', maxsplit=1) print(rs)
String formatted output
# format() can be equivalent to a placeholder # You can use {} in the string to replace the original required %s, and in the .format() after the string, fill in the string you need str1 = 'My name is {},welcome my hurt my {}'.format('HaiMan', 'Baby') print(str1) # The format() placeholder should be named to be familiar with the name str2 = 'dear user{name},Hello! You spent a total of this month{money}Yuan,' \ 'Coincidentally, you also spent last month{money}Yuan,' \ 'Once again congratulations to the user{name},be our VIP user!'.format(name='tony', money='8888') print(str2) # format() index value and support repeated use str3 = 'dear user{0},Hello! You spent a total of this month{1}Yuan,' \ 'Coincidentally, you also spent last month{1}Yuan,' \ 'Once again congratulations to the user{0},be our VIP user!'.format('tony', '8888') print(str3) ''' format()Focus on usage, get the data entered by the user, and complete the formatted output of the string ''' name = input('name>>>>:') age = input('age>>>>:') info_our = f'lad{name},You this year{age}Years old!' print(info_our)
Case swap in strings
''' case dependent variable name.upper() variable name.lower() ''' str1 = 'Open The Door! FBI!' # All uppercase The reason why you need to use the variable name to receive is because the string type is an immutable type rs = str1.upper() print(rs) # All lowercase The reason why you need to use the variable name to receive is because the string type is an immutable type rs = str1.lower() print(rs)
Practical application - image verification code ignores case
''' Image verification code:Generate a verification code without unified capitalization and show it to the user Get the verification code entered by the user Convert the verification code entered by the user and the verification code originally generated to uppercase or lowercase and then compare ''' code1 = '98TftF' print(code1) user_code = input('please enter verification code:') if user_code.upper() == code1.upper(): print('Verification passed!') else: print('verification failed!')
Check if a string is a pure number
''' variable name.isdigit() ''' count = 0 age = '18' while count < 3: digit = input('Please enter the age you want to guess:').strip() if digit.isdigit() == False: print('Please key in numbers!') elif digit != age: print('Brainstorm!') count +=1 else: print('You guessed it right!') break
replaces what is specified in a string
''' replace(' ',' ') The quotation marks in the brackets are the content that needs to be replaced, and the quotation marks in the front are the content to be replaced ''' str = 'My name is Jason,pleas love me!'.replace('Jason', 'tony') print(str) ''' Can be replaced one by one from left to right ''' str = 'My name is Jason,pleas love me!' \ ',Jason,Jason,Jason,Jason'.replace('Jason', 'tony', 3) print(str)
concatenation of strings
''' Splice directly with the plus sign ''' str1 = 'hello' str2 = 'world' str3 = str1 +' '+ str2 print(str3) ''' 'Need to add string'.list Characters can be added and the list becomes a string ''' ls = ['hello', 'world','hello', 'world'] ls1 = '|'.join(ls) print(ls1, type(ls1))
Count the number of occurrences of the specified character
''' variable name.count('characters to be counted') ''' str1 = 'Shark babay do do do do do do do' rs = str1.count('do') print(rs)
Determine the beginning or end of a string
''' variable name.startswith('characters to be judged') ''' str1 = 'To live or to die is a question' is_TO = str1.startswith('To') is_tion = str1.endswith('tion') print(is_tion) print(is_TO)
4. The bool value of the basic data type
Overview:
Boolean value( bool): only two results True,False,Used to indicate right or wrong. The default is False value: 0, None,Empty strings, empty collections, empty dictionaries, etc. Naming conventions for booleans: is_delect,is_alive Grammatical structures: variable name = True variable name = False eg: is_delect = False is_alive = True
5. tuple of basic data types
Overview:
Tuple: Immutable sequence of Python object sequence The values in the tuple cannot be changed arbitrarily Grammatical structures: variable name = (Various data types, various data types) eg: tuple_student = ('Jason', 'tom', 'tony', 'Maria')
Built-in method:
type conversion
''' Grammatical structures: tuple() support for The data types of the loop can be converted into tuples ''' lst = [1, 2, 3, 4, 5, 6] re = tuple(lst) print(lst) print(re)
index value
''' Grammatical structures: variable name[subscript] ''' tup = (1, 2, 3, 4) print(tup[0])
interval, direction
''' Grammatical structures: variable name[start subscripting: end subscript: step size] ''' tup = (1, 2, 3, 4) print(tup[1: 3: 2])
Count the number of data values in a tuple
''' len(variable name) ''' tup = (1, 2, 3, 4) print(len(tup))
Count the number of occurrences of a data value in a tuple
''' Count the number of occurrences of a data value in a tuple variable name.count() Fill in the data values to be counted in parentheses ''' tup = (1, 2, 3, 4) print(tup.count(2))
The index value of the specified data value in the statistics tuple
''' The index value of the specified data value in the statistics tuple Grammatical structures: variable name.index() Fill in the data value that needs the index value in the brackets ''' tup = (1, 2, 3, 4) print(tup.index(3))
Notes on Tuples
1,If there is only one data value in the tuple, the comma must not be less 2,The memory address bound by the index within the tuple cannot be modified(Note the distinction between mutable and immutable) 3,Tuples cannot add or delete data
6. A collection of basic data types (set)
Overview:
Collections: Collections are unordered like dictionaries The data within the collection is not repeatable Grammatical structures: variable name = {Various data types, various data types} eg: set_Teacher = {'Jason', 'Tom', 'Tony', 'Maria'}
Built-in method:
type conversion
''' set() The data in the collection must be of immutable type (integer, float, string, tuple) The data in the collection is also unordered, there is no index ''' set_num = [1, 2, 3, 4, 5, 6, 7] re = set(set_num) print(re)
deduplication
''' Grammatical structures: set() Deduplication can be done directly by using type conversion Collection deduplication cannot preserve the original data ''' set_1 = {11, 11, 11, 22, 22, 11, 22, 11, 22, 33, 22} set_1 = set(set_1) print(set_1)
Relational operations (multi-difference check between groups)
''' & effect: find common data values & Applications eg: users per platform ID are unique The result of this operator is to display the same data value ''' name = {'Jason', 'Tony', 'Tom', 'Sandy', 'Oscar'} name1 = {'Jason', 'Jack', 'Mariya', 'Tony'} print(name & name1) ''' - effect Find unique data values - Applications eg: In the friend list of two people, their unique friends The result of this operation displays the data unique to the previous variable ''' name = {'Jason', 'Tony', 'Tom', 'Sandy', 'Oscar'} name1 = {'Jason', 'Jack', 'Mariya', 'Tony'} print(name - name1) ''' | effect find all data values | Applications eg: In the friend list of two people, all the friends The result of this operation displays all the data values of the two variables (only one is displayed if it is repeated) ''' name = {'Jason', 'Tony', 'Tom', 'Sandy', 'Oscar'} name1 = {'Jason', 'Jack', 'Mariya', 'Tony'} print(name | name1) ''' ^ effect find all data values ^ Applications eg: In the friend list of two people, their unique friends The result of this operation displays the data values that are unique to each of the two variables ''' name = {'Jason', 'Tony', 'Tom', 'Sandy', 'Oscar'} name1 = {'Jason', 'Jack', 'Mariya', 'Tony'} print(name ^ name1)
parent set, subset
''' Parent set, subset means contain and be contained ''' name = {'Jason', 'Tony', 'Tom', 'Sandy', 'Oscar', 'Jack', 'Mariya'} name1 = {'Jason', 'Jack', 'Mariya', 'Tony'} print(name > name1)
7. Dictionary of basic data types (dict)
Overview:
dictionary( dict): It is used to store data with a mapping relationship. The dictionary is equivalent to saving two sets of data, one of which is the key data, called key;Another set of data is available via key to visit, known as value. The whole is called a key-value pair. Grammatical structures: variable name = {'key': data value} eg: dict_demo = {'name': 'HaiMan', 'age': 18, 'sex': 'man' }
Built-in method:
type conversion
''' Dictionary type conversion: dict(data to be converted) The conversion of the dictionary is generally not carried out using keywords, but manual conversion is used '''
dictionary value
''' according to k value (deprecated) Grammatical structures: variable name['k key'] ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } print(user_dict['username']) ''' get()method value (recommended) Grammatical structures: variable name.get('k key') get()and press K The difference in value: according to k value, if entered k If there is no key dictionary, the program will report an error get()The method takes the value, if the input k There is no key in the dictionary, it will return None ''' print(user_dict.get('age'))
Modify value data and add key-value pairs
''' Modify value data Grammatical structures: variable name['K key'] = 'modified data' if[]inside K If the key does not exist, a new key-value pair will be added. ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } print(user_dict['username']) user_dict['hobby'] = 'PingPang' print(user_dict) user_dict['sex'] = 'man' print(user_dict)
delete data
''' delete data Grammatical structures: del variable name['K key'] del Deleted data can no longer be recalled variable name.pop('K key') pop()Method to delete data can also be called once ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } del user_dict['username'] print(user_dict) re = user_dict.pop('age') print(user_dict) print(re)
Count the number of key-value pairs in the dictionary
''' Count the number of key-value pairs in the dictionary Grammatical structures: len() ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } long = len(user_dict) print(long)
Dictionary Three Musketeers:
Get all the keys in a dictionary at once
Get all the values in the dictionary at once
Get all the key-value pair data in the dictionary at once
''' Grammatical structures: Get all the keys in a dictionary at once Grammatical structures: variable name.keys() Get all the values in the dictionary at once Grammatical structures: variable name.values() Get all the key-value pair data in the dictionary at once Grammatical structures: variable name.items() ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } print(user_dict.keys()) print(user_dict.values()) print(user_dict.items())
Quickly generate dictionaries with the same data values
''' Quickly generate dictionaries with the same data values Grammatical structures: dict.fromkeys(['K key 1','K key 2','K key 3'],[data value]) The data value produced by this method will be assigned to all K keys, all K The data value of the key is the same Question: how to give k key assignment? ''' dict_user = dict.fromkeys(['name', 'age', 'sex'], []) print(dict_user) dict_user['name'].append('HaiMan') dict_user['age'].append('18') dict_user['sex'].append('man') print(dict_user)
Add key-value pairs to the original dictionary
''' Add key to dictionary Grammatical structures: variable name.setdefault('K key', 'data value') If the dictionary you added already exists K key, then it will not continue to add ,The original data value will not be changed ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } res = user_dict.setdefault('sex', 'man') print(user_dict, res)
popup key-value pair
''' Pops key-value pairs in a dictionary Grammatical structures: variable name.popitem() This method cannot specify which key-value pair to pop up, The pop-up key-value pair is LIFO, that is, the last key-value pair is popped up first, and so on. ''' user_dict = {'username': 'HanMan', 'age': 18, 'hobby': 'basketball' } user_dict.popitem() print(user_dict)