Yesterday's review
The cycle structure of for Return
for Variable name in Iteration objects The loop body
The iteration object can be a string 、 list 、 Dictionaries 、 Tuples 、 aggregate , A list of them 、 Tuple and set usage are consistent
String is output according to the value of a single character
The list is output according to one data value
The dictionary can only get k value , its v Value does not show
range
for Variable name in range() The loop body
The first is range( Number one )
The result of loop traversal is from 0 Number from start to total -1
The second is range( Number one , Value two )
The first value refers to the starting position , The second value refers to the end position , This situation can be summarized as “ Head and tail ”
The third is range( Number one , Value two , Value three )
An additional value is added to the second one , This number is called the interval number , Is to take values every few numbers , It can also be seen as the arithmetic sequence we learn in mathematics
range The actual case of
Web crawler :python The code simulates the network data request to obtain data
Find the rules of the web address , Just use for Loop plus placeholder simple web crawler can be implemented
for+break
break Is to terminate the cycle
for+continue
continue Is to jump out of this cycle , So let's move on to the next cycle
for+else
At the end of the cycle , Normal output , And for At the same level
What to learn today
Introduction to the built-in methods of data types
Concept : Each data type has its own functions
data type . Method name ()
The built-in methods using data types uniformly use period characters , There are too many built-in methods for some data types , You can make a general note until you look familiar , Find your desired function through automatic prompt when using
Integer related methods
keyword :int()
Built-in methods : No, , An integer is an integer , It is mainly used for calculation , So there are no built-in methods
Type conversion : It must comply with the situation that all internal numbers are pure numbers ,int( What needs to be transformed )
print(type(int('12345678'))) # If the string is a pure number, it can be converted print(type(int('1nuuuuuh46781'))) # The string must be a pure number before it can be converted print(type(int('67567.33'))) # The decimal point counts as one character , So you can't
Base conversion :
Binary system octal Decimal system Hexadecimal , We use the decimal system in our daily life
Decimal to other decimal
bin() Is to convert decimal to binary 0b Is the identification of binary numbers
print(bin(100)) # 0b1100100
oct() Is to convert decimal to octal 0o Is the identification of octal numbers
print(oct(100)) # 0o144
hex() Is to convert decimal to hexadecimal 0x64 0x Is the identification of a hexadecimal number
print(hex(100)) # 0x64
If the number is not preceded by any identification , The default is decimal
Other decimal conversions
Through the unique identification of each hexadecimal , We can be the decimal system of which base conversion , Similarly, we can also artificially specify the hexadecimal number
print(int(0b1100100)) # 100 print(int(0o144)) # 100 print(int(0x64)) # 100 print(int('0b1100100', 2)) # 100 print(int('0o144', 8)) # 100 print(int('0x64', 16)) # 100
Floating point correlation methods
keyword :float()
Built-in methods : No, , It is mainly used to participate in mathematical operations
Type conversion :
Contention for type conversions to floating point types , It's a little better than an integer , Can identify a decimal point , But only one
print(float('123')) # 123.0 print(type(float('123'))) # float print(float('123a123')) print(float('123.12')) # Can identify a decimal point print(float('123.123.1.2.2.2.2.2.2')) # Can not be
A special case : Mainly for Boolean values ,False Namely 0.0,True Namely 1.0
Additional explanation :python Not sensitive to numbers , It's easy to make a mistake , It may be distorted if you calculate , But it can still do many things , What is powerful is not itself , Some of its modules , Its shortcomings can be modified through modules
String related methods
keyword :str()
Built-in methods :
There is an index value for the expected value of the string 、 Slice value 、 interval / Direction ,Index value : Single character Support negative numbers
str = 'hello world' print(str[0]) # h # Support the retrieval of negative numbers print(str[-1])
You can get whatever you want ,
Slice value : Multiple characters
str = 'hello world' print(str[0:4]) # hell print(str[-1:-4]) # Can 't get value print(str[-4:-1]) # orl print(str[-1:-4:-1]) # dlr You can use the plus or minus one of the third parameter Control direction
The numbers represent the index , The same is true of ' Head and tail ' The concept of ,
The order of slices is left to right by default , When slicing in the negative direction, you should pay attention to
interval / Direction
str = 'hello world' print(str[:]) # Write nothing , By default, all print(str[::2]) # It means that the interval is one by one hlowrd print(str[::3]) # It means one of two intervals hlwl
Count the number of characters in a string
print(len(str)) # 11
Note that a space in a string is also a character , When counting the number of strings, it will also be included
Remove the characters from the beginning and end of the string
.strip() By default, the leading and trailing space symbols are removed , It is often used when we log inname = ' zhang ' print(len(name)) # Start name The length of the string is 9 print(name.strip(), len(name.strip())) # By removing The length is only 5 res = name.strip()
Note that it does not change the original value , Just recreated a new data , If you want to permanently save the new value, you can also bind a name to the value
.strip('\(')) Can be used to remove the specified value .lstrip('\)')) Remove the specified value on the left
.rstrip('$')) Remove the specified value on the rightCuts a string according to the specified character
When continuous characteristic symbols appear in the string , You can consider using character cutting , After cutting the string, the result is a listinfo = 'zhan|123|run' res = info.split('|') # After cutting the string, the result is a list print(res, type(res)) # ['zhang', '123', 'run'] <class 'list'>
.split('|', maxsplit=1)) Inside maxsplit From left to right Cut only once ['zhang', '123|run']
.rsplit('|', maxsplit=1)) Means from right to right Cut only once ['zhang|123', 'run']
String case related
.lower() Converts all uppercase characters in a string to lowercase characters.upper() Converts all uppercase characters in a string to lowercase characters
Be careful : Just the conversion between letters , Numbers 、 Symbol 、 Spaces, etc. cannot participate in the conversion.islower() Determine whether all letters in the string are all lowercase
.isupper() # Determine whether all the letters in the string are all uppercase
Formatted output of string
key word :.formatMode one : Equivalent to %S placeholder , Edit the text before , Where space occupation is required, enter {} Come to the booth , Multiple placeholders can be set , And then through Variable name .format(' Data values ',' Data values '......)
res1 = 'my name is {} my age is {}' print(res1.format('zhangran', 18))
Mode two : Use index values , First use {} To carry on the placeholder , Enter the index , Then input values in index order when using ,, It can be used multiple times
res2 = 'my name is {0} my age is {1} {0} my friends always called me {2}' print(res2.format('zhangran', 18, 'zhangxiaoran'))
Mode three : Keyword values are supported ( Press k Value ), It also supports reuse in {} Input k value , Then, when using, enter k The data value of value is OK
res3 = '{name} {name} {age} my name is {name} my age is {age}' print(res3.format(name='jason', age=18))
Mode 4 : Use variable names , First bind the data value to the variable , And then in use directly in {} Enter the variable name in the , It can also be used repeatedly , The most recommended method
name = 'zhangran' age = 18 print(f'my name is {name} my age is {age} {name} {age}')
Counts the number of occurrences of the specified character in the string
keyword :.count(), The operation of the underlying implementation is to use for loop , It is used internally to compare whether it is consistent with what you enter , And then add it up , The results of
str = 'jjsokjflpkfpzfifmcuioijjjALJAGAGAGFETEYEUEJDHDGDGSBSBS' print(str.count('j')) # 6 print(str.count('GA')) # 2
Determine the beginning or end of a string
.startswith Represents the beginning character
.endswith Represents the ending character
What you can find is a single character , It can also be multiple characters , The result returned is a Boolean value
res = 'jason say ha ha ha heiheihei' print(res.startswith('jason')) print(res.startswith('j')) print(res.startswith('b')) print(res.endswith('heiheihei')) print(res.endswith('hei')) print(res.endswith('h'))
String replacement
keyword :.replace
Grammatical structure : Variable name .replace('old_str','new_str' ,1), Replace... From left to right , The number of replacements can be specified
String splicing
keyword :''.join([]), The previous string , Followed by .join(),join() Write a list in it 、 Tuples , String splicing , But the data in the list must be of string type
res1 = 'hello' res2 = 'world' print(''.join(['hello', 'world', 'hahaha'])) # join Method splicing print('|'.join(['hello', 'world', 'hahaha'])) # join Method splicing print('$'.join(['jason', 'say', 666])) # All data in the list must be of string type Report errors !!!
Strings support plus splicing
res1 = 'hello' res2 = 'world' print(res1 + res2)
String support multiply sign repetition
res1 = 'hello' res2 = 'world' print(res1 * 10)
Determine whether the string is a pure number
key word :.isdigit(), The return is a Boolean value , Judge whether the string is a pure number , It can be used in the case of login , It can prevent the website from crashing
print('123'.isdigit()) # True print('123a'.isdigit()) # False print(''.isdigit()) # False
Find the index value corresponding to a character
res = 'jason say ha ha ha heiheihei'
.index An index that can be used to find characters
.find It can also be used to find the index of characters
.index And .find Can be used to find the index , But find out if there are any characters in a certain range , If the former is not available, an error will be reported , What the latter does not return is -1,-1 It means that there is no , Report errors , There is no way to implement
print(res.find('d',0,5)) # -1 prnt(res.index('d',0,5)) # Will report a mistake
Text related operations
.title(), title case
.capitalize(), Only the first letter is capitalized
res = 'my name is zhangran' print(res.title()) # My Name Is Zhangran print(res.capitalize()) # My name is zhangran
Type conversion :
Any data type can be converted to string type , He just added... To the outermost layer ’‘, It is compatible with all data typesprint(str(12), type(str(12))) # 12 <class 'str'> print(str(123.11), type(str(123.11))) # 123.11 <class 'str'> print(str([1, 2, 3, 4]), type(str([1, 2, 3, 4]))) # [1, 2, 3, 4] <class 'str'> print(str({'name': 'jason'}), type(str({'name': 'jason'}))) # {'name': 'jason'} <class 'str'> print(str(True), type(str(True))) # True <class 'str'> print(str((1, 2, 3, 4)), type(str((1, 2, 3, 4)))) # (1, 2, 3, 4) <class 'str'> print(str({1, 2, 3, 4}), type(str({1, 2, 3, 4}))) # {1, 2, 3, 4} <class 'str'>
List related methods
keyword :list()
Type conversion :
Integer and floating-point types cannot be converted directly to lists ,list() It's really just a for loop , It can be for The data type of a loop can be converted to a list
Built-in methods :
Index value
str = ['sjkah','jksal','ajshd','kasjhd','aslj','akJSBS'] print(str[0]) # h # Support the retrieval of negative numbers print(str[-1])
Slice value
str = ['sjkah','jksal','ajshd','kasjhd','aslj','akJSBS'] print(str[0:4]) print(str[-1:-4]) print(str[-4:-1]) print(str[-1:-4:-1])
interval / Direction
str = ['sjkah','jksal','ajshd','kasjhd','aslj','akJSBS'] print(str[:]) # Write nothing , By default, all print(str[::2]) # It means that the interval is one by one print(str[::3]) # It means one of two intervals
Count the number of data in the list
print(len(str)) # 11
Homework after class
# 1. Act as a database based on string to complete user login ( Based on practice )
# data_source = 'jason|123' # A user data
# Get user name and password Split the above data to verify whether the user information is correct
# Split into user name and password , Press | Split
data_source = 'jason|123'
res = data_source.split('|')
# print(res) # ['jason', '123']
data_name = res[0]
data_pwd = res[1]
# print(data_name,data_pwd)
# User login code
username = input(' enter one user name :')
password = input(' Input password :')
"""
1. Judge whether the user input is correct , Login success and failure
2. Determine whether the input data is the user of the database
3. Extraction of database users
print(res) # ['jason', '123'] At this point, the string has been split into lists
data_name = res[0]
data_pwd = res[1]
"""
if username == data_name and password == data_pwd:
print(' Login successful ')
else:
print(' Login failed ')
# 2. User login based on list acting as database ( High practice ) # Multiple user data
# data_source = ['jason|123', 'kevin|321','oscar|222']
data_source2 = ['jason|123', 'kevin|321', 'oscar|222']
# Take out each value first , And then split
data1 = data_source2[0].split('|')
data2 = data_source2[1].split('|')
data3 = data_source2[2].split('|')
print(data1, data2, data3) # ['jason', '123'] ['kevin', '321'] ['oscar', '222']
# Find the value after splitting
data_name1 = data1[0]
data_pwd1 = data1[1]
data_name2 = data2[0]
data_pwd2 = data2[1]
data_name3 = data3[0]
data_pwd3 = data3[1]
# Get user input data
# If the user name is jason And the code is 123, Or the input is kevin And the code is 321, Or the input is oscar And the code is 321, Login successful , Otherwise failure
username = input(' enter one user name :')
password = input(' Input password :')
if username == data_name1 and password == data_pwd1:
print('jason, Login successful ')
elif username == data_name2 and password == data_pwd2:
print('kevin, Login successful ')
elif username == data_name3 and password == data_pwd3:
print('oscar, Login successful ')
else:
print(' Login failed ')