程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

3.3python foundation03

編輯:Python

List of articles

  • Four 、 String common operation method :
    • 4.1 len(): Get string length or number of bytes
    • 4.2split(): Split string
    • 4.3join() Method : Merge strings
    • 4.4 count() Method : Count the number of string occurrences
    • 4.5 find() Method : Detects whether a string contains a substring
    • 4.6index() Method : Detects whether a string contains a substring
    • 4.7 startswith() and endswith() Method
      • startswith() Method
      • endswith() Method
    • 4.8 String case conversion
      • title() Method
      • lower() Method
      • upper() Method
    • 4.9 strip: Remove the space in the string
    • 4.10 replace() String substitution
    • 4.11 format() Format output
    • 5、 ... and 、 Commonly used built-in functions use :
  • 6、 ... and 、 Process control
    • 6.1 if sentence
      • 6.1.1 if else Detailed explanation of conditional statements
    • 6.1.2 if else How to judge whether the expression is true
    • 6.1.3if Statement nesting
    • 6.1.4 pass sentence
    • 6.1.5 assert Assertion function
    • 6.2 while Loop statement
      • 6.2.1 while Loop statement details
    • 6.3for loop
    • 6.4 break Usage details
    • 6.5 continue Usage of

Four 、 String common operation method :

4.1 len(): Get string length or number of bytes

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

4.2split(): Split string

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: Represents the string to be split ;
  • sep: Used to specify separator , Can contain multiple characters . This parameter defaults to None, Indicates all empty characters , Including Spaces 、 A newline “\n”、 tabs “\t” etc. .
  • maxsplit: Optional parameters , Used to specify the number of divisions , The number of substrings in the final list is at most maxsplit+1. If not specified or designated as -1, It means that there is no limit to the number of segmentation .
>>> 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']
>>>

4.3join() Method : Merge strings

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 :

  • newstr: Represents the new string generated after the merge ;
  • str: Used to specify the separator when merging ;
  • iterable: Source string data for merge operation , Allow to list 、 Tuples and so on .

【 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'

4.4 count() Method : Count the number of string occurrences

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 :

  • str: Represents the original string ;
  • sub: Represents the string to retrieve ;
  • start: Specify the starting location of the search , That is, from where to start the detection . If you don't specify , Search from scratch by default ;
  • end: Specify the end of the retrieval , If you don't specify , It means to search all the way to the end .

【 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

4.5 find() Method : Detects whether a string contains a substring

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 :

  • str: Represents the original string ;
  • sub: Represents the target string to retrieve ;
  • start: Indicates where to start the search . If you don't specify , By default, search from the beginning ;
  • end: Indicates the end position of the end Retrieval . If you don't specify , The default is to search until the end .

【 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.

4.6index() Method : Detects whether a string contains a substring

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 :

  • str: Represents the original string ;
  • sub: Represents the substring to retrieve ;
  • start: Indicates the starting position of the search , If you don't specify , Search from scratch by default ;
  • end: Indicates the end of the search , If you don't specify , The default is to retrieve all the way to the end .

【 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

4.7 startswith() and endswith() Method

startswith() Method

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 :

  • str: Represents the original string ;
  • sub: Substring to retrieve ;
  • start: Specify the starting position of the search index , If you don't specify , By default, search from the beginning ;
  • end: Specifies the end location index of the retrieval , If you don't specify , By default, the retrieval is always at the end .

【 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

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 :

  • str: Represents the original string ;
  • sub: Represents the string to retrieve ;
  • start: Specify the starting position index at the beginning of retrieval ( The index value corresponding to the first character of the string is 0), If you don't specify , Search from scratch by default .
  • end: Specifies the end location index of the retrieval , If you don't specify , The default is to retrieve until the end .

【 example 4】 retrieval “c.biancheng.net” Whether or not to “net” end .

>>> str = "c.biancheng.net"
>>> str.endswith("net")
True

4.8 String case conversion

title() Method

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

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() Method

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'

4.9 strip: Remove the space in the string

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 .

4.10 replace() String substitution

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 :

  • oldvalue It's necessary . The string to retrieve .
  • newvalue It's necessary . Replace the old value string .
  • count Optional . Numbers , Specify the number of occurrences of the old value to replace . The default is all occurrences .

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

4.11 format() Format output

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"))

5、 ... and 、 Commonly used built-in functions use :

https://m.php.cn/article/471822.html

  • reversed: Reversing the sequence generates new iterable objects
>>> 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]
  • sorted: Sort the objects that can be iterated , Returns a new list
>>> 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']
  • zip: Aggregates elements at the same location in each passed iterator , Returns a new tuple type iterator
>>> 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)]
  • dir() function

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']
  • help() function

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 .

  • id: Returns the unique identifier of the object
>>> a = 'some text'
>>> id(a)
69228568
  • type: Returns the type of the object , Or create a new type based on the parameters passed in
>>> type(1) # Returns the type of the object 
<class 'int'>
  • len: Returns the length of the object
>>> 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 

6、 ... and 、 Process control

6.1 if sentence

6.1.1 if else Detailed explanation of conditional statements

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 .

6.1.2 if else How to judge whether the expression is true

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 ')

6.1.3if Statement nesting

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 ")

6.1.4 pass sentence

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 ")

6.1.5 assert Assertion function

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)

6.2 while Loop statement

6.2.1 while Loop statement details

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 !")

6.3for loop

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)

6.4 break Usage details

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 ")

6.5 continue Usage of

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="")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved