len The basic syntax format of the function is :
len(string)
among string Used to specify the string to be length counted .
for example , Define a string , The content is “http://c.biancheng.net”, And then use len() Function to evaluate the length of the string , The execution code is as follows :
>>> a='http://c.biancheng.net'
>>> len(a)
22
split() Method can be used to cut a string into multiple substrings according to the specified separator , These substrings are saved to the list ( Does not contain separators ), Feedback back as the return value of the method . The basic syntax format of this method is as follows :
str.split(sep,maxsplit)
The meanings of the parameters in this method are respectively :
>>> str = "C Chinese language network >>> c.biancheng.net"
>>> str
'C Chinese language network >>> c.biancheng.net'
>>> list1 = str.split() # Split with default separator
>>> list1
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>> list2 = str.split('>>>') # Use multiple characters for segmentation
>>> list2
['C Chinese language network ', ' c.biancheng.net']
>>> list3 = str.split('.') # use . No split
>>> list3
['C Chinese language network >>> c', 'biancheng', 'net']
>>> list4 = str.split(' ',4) # Use spaces to divide , And stipulates that it can only be divided into 4 Substring
>>> list4
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>> list5 = str.split('>') # use > Character segmentation
>>> list5
['C Chinese language network ', '', '', ' c.biancheng.net']
>>>
It should be noted that , In unspecified sep When parameters are ,split() Method uses null characters for segmentation by default , But when there are consecutive spaces or other empty characters in the string , Will be treated as a separator to split the string , for example :
>>> str = "C Chinese language network >>> c.biancheng.net" # contain 3 Consecutive spaces
>>> list6 = str.split()
>>> list6
['C Chinese language network ', '>>>', 'c.biancheng.net']
>>>
join() Method is also a very important string method , It is split() The inverse of method , Used to list ( Or tuples ) Multiple strings contained in are concatenated into one string .
join() The syntax of the method is as follows :
newstr = str.join(iterable)
The meanings of parameters in this method are as follows :
【 example 1】 Merge the strings in the list into one string .
>>> list = ['c','biancheng','net']
>>> '.'.join(list)
'c.biancheng.net'
【 example 2】 Combine strings in tuples into one string .
>>> dir = '','usr','bin','env'
>>> type(dir)
<class 'tuple'>
>>> '/'.join(dir)
'/usr/bin/env'
count Method to retrieve the number of times a specified string appears in another string , If the retrieved string does not exist , Then return to 0, Otherwise, return the number of occurrences .
count The syntax of the method is as follows :
str.count(sub[,start[,end]])
In this way , The specific meaning of each parameter is as follows :
【 example 1】 Retrieve string “c.biancheng.net” in “.” Number of occurrences .
>>> str = "c.biancheng.net"
>>> str.count('.')
2
【 example 2】
>>> str = "c.biancheng.net"
>>> str.count('.',1)
2
>>> str.count('.',2)
1
I talked about it before. , The retrieval value corresponding to each character in the string , from 0 Start , therefore , Retrieve values in this example 1 Corresponding to No 2 Characters ‘.’, From the output we can analyze , Retrieve from the specified index location , It also includes the index location .
【 example 3】
>>> str = "c.biancheng.net"
>>> str.count('.',2,-3)
1
>>> str.count('.',2,-4)
0
find() Method to retrieve whether a string contains a target string , If you include , The index of the first occurrence of the string is returned ; conversely , Then return to -1.
find() The syntax of the method is as follows :
str.find(sub[,start[,end]])
The meanings of parameters in this format are as follows :
【 example 1】 use find() Method retrieval “c.biancheng.net” First time in “.” Location index of .
>>> str = "c.biancheng.net"
>>> str.find('.')
1
【 example 2】 Manually specify the location of the starting index .
>>> str = "c.biancheng.net"
>>> str.find('.',2)
11
【 example 3】 Manually specify the location of the start index and end index .
>>> str = "c.biancheng.net"
>>> str.find('.',2,-4)
-1
At index (2,-4) The string between is “biancheng”, Because it does not contain “.”, therefore find() The return value of the method is -1.
Same as find() The method is similar to ,index() Method can also be used to retrieve whether the specified string is included , The difference is , When the specified string does not exist ,index() The method throws an exception .
index() The syntax of the method is as follows :
str.index(sub[,start[,end]])
The meanings of parameters in this format are :
【 example 1】 use index() Method retrieval “c.biancheng.net” First time in “.” Location index of .
>>> str = "c.biancheng.net"
>>> str.index('.')
1
【 example 2】 When retrieval fails ,index() It throws an exception .
>>> str = "c.biancheng.net"
>>> str.index('z')
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
str.index('z')
ValueError: substring not found
startswith() Method to retrieve whether a string begins with the specified string , If it's a return True; Instead, return to False. The syntax format of this method is as follows :
str.startswith(sub[,start[,end]])
The specific meaning of each parameter in this format is as follows :
【 example 1】 Judge “c.biancheng.net” Whether or not to “c” Substring start .
>>> str = "c.biancheng.net"
>>> str.startswith("c")
True
【 example 2】
>>> str = "c.biancheng.net"
>>> str.startswith("http")
False
【 example 3】 Retrieve from the specified location .
>>> str = "c.biancheng.net"
>>> str.startswith("b",2)
True
endswith() Method to retrieve whether a string ends with a specified string , If so, return True; Otherwise, return False. The syntax format of this method is as follows :
str.endswith(sub[,start[,end]])
The meanings of parameters in this format are as follows :
【 example 4】 retrieval “c.biancheng.net” Whether or not to “net” end .
>>> str = "c.biancheng.net"
>>> str.endswith("net")
True
title() Method is used to capitalize each word in a string , All other letters are lowercase , After the conversion , This method will return the converted String . If there are no characters in the string that need to be converted , This method returns the string intact .
title() The syntax of the method is as follows :
str.title()
among ,str Represents the string to be converted .
【 example 1】
>>> str = "c.biancheng.net"
>>> str.title()
'C.Biancheng.Net'
>>> str = "I LIKE C"
>>> str.title()
'I Like C'
lower() Method is used to convert all uppercase letters in a string to lowercase letters , After the conversion , This method will return the new string . If the string is originally lowercase , The method returns the original string .
lower() The syntax of the method is as follows :
str.lower()
among ,str Represents the string to be converted .
【 example 2】
>>> str = "I LIKE C"
>>> str.lower()
'i like c'
upper() The function and lower() The opposite is true , It is used to convert all lowercase letters in a string to uppercase letters , The return method is the same as the above two methods , That is, if the conversion is successful , Then return the new string ; conversely , Return the original string
upper() The syntax of the method is as follows :
str.upper()
among ,str Represents the string to be converted .
【 example 3】
>>> str = "i like C"
>>> str.upper()
'I LIKE C'
strip() Method is used to delete the left and right spaces and special characters in a string , The syntax format of this method is :
str.strip([chars])
among ,str Represents the original string ,[chars] Used to specify the character to be deleted , Multiple can be specified at the same time , If you don't specify , Spaces and tabs are deleted by default 、 A carriage return 、 Special characters such as line breaks .
【 example 1】
>>> str = " c.biancheng.net \t\n\r"
>>> str.strip()
'c.biancheng.net'
>>> str.strip(" ,\r")
'c.biancheng.net \t\n'
>>> str
' c.biancheng.net \t\n\r'
It is not difficult to see the results of the analysis and operation , adopt strip() It is indeed possible to delete spaces and special characters on the left and right sides of the string , But it doesn't really change the string itself .
replace() Method replaces a specified phrase with another specified phrase .
string.replace(oldvalue, newvalue, count)
The meanings of parameters in this format are as follows :
example : Replace all words that appear “one”:
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
example : Replace the first two occurrences of the word “one”:
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
Be careful : It can be used replace(’ ‘,’') To remove all spaces from the string
The previous section describes how to use % Operator formats and outputs various types of data , This is the early stage. Python Methods provided . since Python 2.6 Version start , String type (str) Provides format() Method to format a string , This section will learn this method .
format() The syntax of the method is as follows :
str.format(args)
In this way ,str Used to specify the display style of the string ;args Used to specify the item to be format converted , If there are more than one , There are commas between .
str=" Website name :{} website :{}"
print(str.format("C Chinese language network ","c.biancheng.net"))
https://m.php.cn/article/471822.html
>>> a = reversed(range(10)) # Pass in range object
>>> a # Type becomes iterator
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']
>>> sorted(a) # Default by character ascii Sort code
['A', 'B', 'a', 'b', 'c', 'd']
>>> sorted(a,key = str.lower) # Convert to lowercase and sort ,'a' and 'A' Have the same value ,'b' and 'B' Have the same value
['a', 'A', 'b', 'B', 'c', 'd']
>>> x = [1,2,3] # length 3
>>> y = [4,5,6,7,8] # length 5
>>> list(zip(x,y)) # Take the minimum length 3
[(1, 4), (2, 5), (3, 6)]
Returns a list of objects or properties in the current scope
dir(obj)
obj Represents the object to view .obj Don't write , here dir() The variables in the current range will be listed 、 Types of methods and definitions .
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
It is used to view the help document of a function or module , Its usage is :
help(obj)
obj Represents the object to view .obj Don't write , here help() Will enter the help subroutine .
>>> a = 'some text'
>>> id(a)
69228568
>>> type(1) # Returns the type of the object
<class 'int'>
>>> len('abcd') # character string
>>> len(bytes('abcd','utf-8')) # Byte array
>>> len((1,2,3,4)) # Tuples
>>> len([1,2,3,4]) # list
>>> len(range(1,5)) # range object
>>> len({
'a':1,'b':2,'c':3,'d':4}) # Dictionaries
>>> len({
'a','b','c','d'}) # aggregate
>>> len(frozenset('abcd')) # Immutable set
Python Medium if else Statements can be broken down into three forms , Namely if sentence 、if else Statement and if elif else sentence , Their syntax and execution flow are shown in table 1 Shown .
#【 example 1】 Use the first selection structure to determine whether the user meets the criteria :
age = int( input(" Please enter your age :") )
if age < 18 :
print(" You're underage , It is recommended to use the software with family members !")
print(" If you have the consent of your parents , Please ignore the above tips .")
# The statement does not belong to if Code block for
print(" The software is in use ...")
#【 example 2】 Improve the code above , Exit the program when you don't meet your age :
import sys
age = int( input(" Please enter your age :") )
if age < 18 :
print(" Warning : You're underage , You can't use the software !")
print(" Minors should study hard , Go to a good University , Serve the motherland .")
sys.exit()
else:
print(" You are an adult , You can use the software .")
print(" Precious time , Please don't waste too much time on the software .")
print(" The software is in use ...")
#【 example 3】 Judge whether a person's figure is reasonable :
height = float(input(" Enter the height ( rice ):"))
weight = float(input(" Enter the weight ( kg ):"))
bmi = weight / (height * height) # Calculation BMI Index
if bmi<18.5:
print("BMI Index is :"+str(bmi))
print(" Underweight ")
elif bmi>=18.5 and bmi<24.9:
print("BMI Index is :"+str(bmi))
print(" normal range , Pay attention to keep ")
elif bmi>=24.9 and bmi<29.9:
print("BMI Index is :"+str(bmi))
print(" Overweight ")
else:
print("BMI Index is :"+str(bmi))
print(" obesity ")
It will judge whether the expression is true from top to bottom , Once you come across a valid expression , Just execute the following block of statements ;
The rest of the code is no longer executed , Whether the following expression holds or not .
Boolean type (bool) There are only two values , Namely True and False,Python Will be able to True treat as “ really ”, hold False treat as “ false ”.
For numbers ,Python Will be able to 0 and 0.0 treat as “ false ”, Think of other values as “ really ”.
For other types , When the object is empty or is None when ,Python They will be treated as “ false ”, Other situations are treated as true
The following expression will treat them as “ false ”:
"" # An empty string
[ ] # An empty list
( ) # An empty tuple
{
} # An empty dictionary
None # Null value
b = False
if b:
print('b yes True')
else:
print('b yes False')
n = 0
if n:
print('n It's not zero ')
else:
print('n It's zero ')
s = ""
if s:
print('s Not an empty string ')
else:
print('s Is an empty string ')
l = []
if l:
print('l It's not an empty list ')
else:
print('l It's an empty list ')
d = {
}
if d:
print('d It's not an empty dictionary ')
else:
print('d It's an empty dictionary ')
if None:
print(' Not empty ')
else:
print(' It's empty ')
Python Code blocks are marked with indentations , Code blocks must be indented , What's not indented is not a block of code . in addition , The same block of code should be indented the same amount , Different indents do not belong to the same code block .
By indenting , When nesting with each other , View logical relationships .
proof = int(input(" Input driver per 100ml The amount of alcohol in the blood :"))
if proof < 20:
print(" Drivers don't constitute alcohol driving ")
else:
if proof < 80:
print(" The driver has become a drunk driver ")
else:
print(" The driver has become drunk ")
pass yes Python Keywords in , Used to get the interpreter to skip over here , Don't do anything? .
age = int( input(" Please enter your age :") )
if age < 12 :
print(" Infants and young children ")
elif age >= 12 and age < 18:
print(" teenagers ")
elif age >= 18 and age < 30:
print(" adults ")
elif age >= 30 and age < 50:
pass
else:
print(" aged ")
assert sentence , Also known as assertion statement , It can be seen as a reduced version of if sentence , It is used to judge the value of an expression , If the value is true , Then the program can continue to execute ; conversely ,Python The interpreter will report AssertionError error .
mathmark = int(input())
# Assert whether the math test score is within the normal range
assert 0 <= mathmark <= 100
# Only when mathmark be located [0,100] Within the scope of , The program will continue
print(" The math test score is :",mathmark)
while Circulation and if Conditional branch statements are similar to , That is, under the condition that ( expression ) If it's true , Will execute the corresponding code block . The difference is , As long as the condition is true ,while You're going to repeat that block of code .
# Initialization conditions of the loop
num = 1
# When num Less than 100 when , Will always execute the loop body
while num < 100 :
print("num=", num)
# Iteration statement
num += 1
print(" The loop ends !")
add = "http://c.biancheng.net/python/"
#for loop , Traverse add character string
for ch in add:
print(ch,end="")
##for Loop to do a numerical loop
print(" Calculation 1+2+...+100 As the result of the :")
# Variables that hold the accumulated results
result = 0
# Get one by one from 1 To 100 These values , And do the accumulation operation
for i in range(101):
result += i
print(result)
##for Loop through lists and tuples
my_list = [1,2,3,4,5]
for ele in my_list:
print('ele =', ele)
##for Loop through Dictionary
my_dic = {
'python course ':"http://c.biancheng.net/python/",\
'shell course ':"http://c.biancheng.net/shell/",\
'java course ':"http://c.biancheng.net/java/"}
for ele in my_dic:
print('ele =', ele)
break Statement can immediately terminate the execution of the current loop , Jump out of the current loop structure . Whether it's while Cycle or for loop , Just execute break sentence , It will directly end the current executing loop body
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
# A simple for loop
for i in add:
if i == ',' :
# End cycle
break
print(i,end="")
print("\n Execute the extracorporeal code ")
and break Statement than ,continue Sentences are less powerful , It will only terminate the execution of the rest of the code in this loop , Proceed directly from the next loop .
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
# A simple for loop
for i in add:
if i == ',' :
# Ignore the rest of this loop
print('\n')
continue
print(i,end="")