Python Introduction to basic grammar ( One )
Common operations for strings include :
To obtain the length of the :len
len Function to get the length of the string .
Find content :find
Finds whether the specified content exists in the string , If it exists, it returns the content in the string First appearance Start position index value of ( from 0 Start calculating ), If it doesn't exist , Then return to -1.
Judge :startswith
,endswith
Determine whether the string starts with / ending
Count the number of occurrences :count
return str stay start and end Between , The number of occurrences in the string
replace content :replace
Replace what is specified in the string , If you specify the number of times count, Then the replacement will not exceed count Time .
Cut string :split
Cut the string by the content of the parameter
Change case :upper
,lower
Convert string to uppercase or lowercase
A space :strip
Go to space
String splicing :join
String splicing
str = "a"
print(str.join('hello'))
#haealalao
# Let's focus on it join, The specified string is added to the middle of each character of the string ( The first and last characters do not add ). It's not often used
Add, delete, modify and search the list
Additive elements
There are several ways to add elements :
append
Add elements at the end
insert
Inserts an element at the specified location
extend
Merge two lists
append
append
The new element is added to the end of the list
name_list = [' Zhang San ', ' Li Si ']
name_list.append(' Wang Wu ')
print(name_list)
#[' Zhang San ', ' Li Si ', ' Wang Wu ']
insert
insert(index, object)
At a designated location index Insert element before object
name_list = [' Zhang San ', ' Li Si ']
name_list.insert(1, ' Xiao Ming ')
print(name_list)
#[' Zhang San ', ' Xiao Ming ', ' Li Si ']
extend
adopt extend
You can add elements from another list to the list one by one
name_list = [' Zhang San ', ' Li Si ']
name_list2 = [' Xiao Li ', ' Xiao Wang ']
name_list.extend(name_list2)
print(name_list)
#[' Zhang San ', ' Li Si ', ' Xiao Li ', ' Xiao Wang ']
Modifying elements
We access list elements by specifying subscripts , So when you modify an element , Assign a value to the specified list subscript .
name_list = [' Zhang San ', ' Li Si ']
print(" Before the change :%s" % name_list)
name_list[1] = ' Xiao Li '
print(" After modification :%s" % name_list)
# Before the change :[' Zhang San ', ' Li Si ']
# After modification :[' Zhang San ', ' Xiao Li ']
Look for the element
So called search , Is to see if the specified element exists , It mainly includes the following methods :
in
and not in
python The common method of searching in is :
in
( There is ), If it exists, the result is true, Otherwise falsenot in
( non-existent ), If not, the result is true, otherwise falsename_list = [' Zhang San ', ' Li Si ']
if ' Wang Wu ' in name_list:
print(' There is ')
else:
print(' non-existent ')
# non-existent
not similar , Just take the opposite
Remove elements
The common ways to delete list elements are :
del
: Delete according to subscript
pop
: Delete the last element
remove
: Delete based on the value of the element
del
name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
del name_list[1]
print(name_list)
#[' Zhang San ', ' Xiao Li ']
pop
name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
name_list.pop()
print(name_list)
#[' Zhang San ', ' Li Si ']
remove
name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
name_list.remove(' Zhang San ')
print(name_list)
#[' Li Si ', ' Xiao Li ']
Python A tuple of is similar to a list , The difference is The element of a tuple cannot be modified . Tuples use braces , Use square brackets for lists .
tuple1 = (1, 2, 3)
print(tuple1[1]) #2
python Modification of tuple data... Is not allowed in , Including elements that cannot be deleted .
Define a tuple with only one element , need Write a comma after the unique element
tuple1 = (1)
print(type(tuple1)) #int
tuple2 = (1,)
print(type(tuple2)) #tuple
Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples Both support slicing .
The syntax of slicing :[ start : end : step ], It can also simplify the use of [ start : end ]
Be careful : The selected interval is from " start " Bit start , To " end " The last one of the first ( Does not include the end bit itself ), The step size represents the selection interval .
# An index is to get an element by subscript
# Slicing is to remove a certain element by subscript
s = 'Hello World!'
print(s)
print(s[4]) # o The... In the string 4 Elements
print(s[3:7]) # lo W Include subscripts 3, Without subscript 7
print(s[1:]) # ello World! From the subscript for 1 Start , Take out All subsequent elements ( No end bit )
print(s[:4]) # Hell Starting from the starting position , Fetch Subscript to be 4 The previous element of ( Excluding the end bit itself )
print(s[1:5:2]) # el From the subscript for 1 Start , Take the subscript 5 The previous element of , In steps of 2( Excluding the end bit itself )
Besides using key Find data , You can also use get To get data
person = {
'name': ' Zhang San ', 'age': 18}
# No pass . attribute , Get value
print(person['name'])
# print(person['email']) # Get what doesn't exist key, Exceptions will occur
print(person.get('name'))
print(person.get('email')) # Get what doesn't exist key, Will get None value , No exceptions
print(person.get('email', '[email protected]')) # Get what doesn't exist key, You can provide a default value .
The data in each element of the dictionary is modifiable , As long as through the key find , You can modify
person = {
'name': ' Zhang San ', 'age': 18}
person['name'] = ' Xiao Li '
print(' The modified value is :%s' % person) # The modified value is :{'name': ' Xiao Li ', 'age': 18}
If you are using Variable name [‘ key ’] = data when , This “ key ” In the dictionary , non-existent , So it's going to add this element
person = {
'name': ' Zhang San ', 'age': 18}
person['email'] = '[email protected]'
print(' The added value is :%s' % person) # The added value is :{'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
Delete the dictionary , There are several kinds of :
del
clear()
del Delete the specified element
person = {
'name': ' Zhang San ', 'age': 18}
del person['age']
print(person) #{'name': ' Zhang San '}
del Delete entire dictionary
person = {
'name': ' Zhang San ', 'age': 18}
del person
print(person) # Report errors :NameError: name 'person' is not defined
clear Empty the whole dictionary , But keep the structure of the dictionary
person = {
'name': ' Zhang San ', 'age': 18}
person.clear()
print(person) #{}
Traversing the dictionary key( key )
person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for s in person.keys():
print(s)
#name
#age
#email
Traversing the dictionary value( value )
person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for s in person.values():
print(s)
# Zhang San
#18
#[email protected]
Traversal dictionary items ( Elements )
person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for i in person.items():
print(i)
#('name', ' Zhang San ')
#('age', 18)
#('email', '[email protected]')
Traversing the dictionary key-value( Key value pair )
person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for k, v in person.items():
print('key yes :%s,value yes :%s' % (k, v))
#key yes :name,value yes : Zhang San
#key yes :age,value yes :18
#key yes :email,value yes :[email protected]
The format of defining a function is as follows :
def Function name ():
Code
After defining the function , It is equivalent to having a code with some functions , Want this code to execute , You need to call it
It's easy to call functions , adopt Function name () To complete the call
Example :
# Defined function
def f1():
print('hello ')
print('world')
f1() # After defining the function , Functions are not executed automatically , You need to call it to
result :
hello
world
After the function is defined , The code in the function body does not execute , If you want to execute the contents of the function body , You need to call the function manually .
Every time a function is called , Functions are executed from scratch , When the code in this function is executed , It means that the call is over .
To make a function more general , For example, you want it to calculate the sum of which two numbers , Let it calculate the sum of which two numbers , When defining a function, you can connect the function to Receive data , That solves the problem , This is the argument to the function
Definition 、 Call a function with parameters To calculate the sum of any two numbers :
def sum(a, b):
print('a The value of is :%s,b The value of is :%s, Calculate and for :%s' % (a, b, a + b))
sum(9, 1) # Positional arguments
sum(b = 1,a = 9) # Key parameters
result :
a The value of is :9,b The value of is :1, Calculate and for :10
a The value of is :9,b The value of is :1, Calculate and for :10
Be careful :
When defining functions , Write the name of the variable to be assigned in parentheses
When the function is called , The data to be calculated is depicted in parentheses
The order of the arguments when the function is called
Parameters in parentheses when defining , Used to receive parameters , be called “ Shape parameter ” ( Formal parameters )
Parameters in parentheses when called , Used to pass to a function , be called “ Actual parameters ” ( The actual parameter )
So-called “ Return value ”, Is the function in the program to complete a thing , Final result to caller
Function with return value
Want to return the result to the caller in the function , You need to use return
Example :
def sum(a, b):
return a + b
# Use a variable to accept the return value of the function
a = sum(9, 1)
print(a) #10
1) Global variables : If a variable is defined outside a function , It can be used in a function , It can also be used in other functions , Such variables are global variables
2) local variable , It's a variable defined inside a function , The scope of action is within this function , That is, you can only use... In this function , Cannot be used outside of a function
local variable :
def f1():
# Defining local variables a
a = 1
print(a)
f1()
Global variables :
# Define global variables a
a = 1
def f1():
print(a)
f1()
Be careful : From the above, we can see all the variables in the program Are defined as global variables to replace local variables , You can't actually do this . When the conditions are met , Use the variable with the smallest scope . It's like 50 Size shoes , Anyone can wear it , But we only wear shoes that fit us .
Open file / create a file
stay python, Use open function , You can open an existing file , Or create a new file .
open( File path , Access pattern )
# Use relative path here , It is under the current directory
f = open("test.txt", 'w')
File path
Absolute path : It refers to the absolute position , A complete description of the location of the target , All directory hierarchies are clear at a glance .
Relative paths : Is the path starting from the folder where the current file is located .
test.txt , Is to find... In the current folder test.txt file
./test.txt , Also search in the current folder test.txt file , ./ Represents the current folder .
…/test.txt , Search from the upper folder of the current folder test.txt file . …/ Represents the upper level folder
demo/test.txt , Find in the current folder demo This folder , And look in this folder test.txt file .
Close file :
# You need to manually create file Folder , Variables are usually named f or fp
f = open("file/test.txt", 'w')
# Close this file
f.close()
Access pattern :
Writing data (write)
Use write()
Can complete writing data to file
# w Mode if the file exists , The contents of the file will be emptied first , And then write . If the mode changes to a, Will execute the append operation
f = open("test.txt", 'w')
f.write('hello world\n' * 3)
f.close()
Reading data (read)
Use read(num)
You can read data from a file ,num Represents the length of data to read from the file ( Unit is byte ), If no incoming
num, That means reading all the data in the file
f = open("test.txt", 'r')
content = f.read(2) # Read at most 2 Data
print(content)
content = f.read() # Continue reading all remaining data from the last read position
print(content)
f.close()
Be careful :
"r"
, Then you can omit open('test.txt')
Reading data (readline)
readline Only used to read one line of data .
f = open("test.txt")
content = f.readline()
print(content)
content = f.readline()
print(content)
f.close()
Reading data (readlines)
readlines
The contents of the whole file can be read at one time in the form of lines , And the return is a list , List of each of these behaviors
An element .
f = open("test.txt")
content = f.readlines()
print(content)
f.close()
Through file operation , We can write strings to a local file . however , If it's an object ( For example, a list of 、 Dictionaries 、 Tuples etc. ), There is nothing
Can't write directly to a file , This object needs to be serialized , Then it can be written to the file .
Through file operation , We can write strings to a local file . however , If it's an object ( For example, a list of 、 Dictionaries 、 Tuples etc. ), There is nothing
Can't write directly to a file , This object needs to be serialized , Then it can be written to the file .
Design a protocol , According to some rules , Convert the data in memory into a sequence of bytes , Save to file , This is serialization , conversely , From the word of the file
Restore the section sequence to memory , It's deserialization .
object —》 Byte sequence Namely serialize
Byte sequence –》 object Namely Deserialization
Python Provided in JSON This module is used to serialize and deserialize data .
JSON modular
JSON(JavaScriptObjectNotation
, JS Object shorthand ) Is a lightweight data exchange standard .JSON The essence of is string .
Use JSON Implement serialization
JSON Provides dump and dumps Method , Serialize an object .
dumps Method Is used to convert objects into strings , It does not have the ability to write data to a file .
f = open("test.txt", 'w')
person = ['zs', 'ls']
# Import json Module into this file
import json
# serialize , take python The object becomes json character string
names = json.dumps(person)
f.write(names)
f.close()
dump Method You can convert an object to a string at the same time , Specify a file object , Write the converted String to this file
f = open("test.txt", 'w')
person = ['zs', 'ls']
# Import json Module into this file
import json
names = json.dump(person, f)
f.close()
Use JSON Implement deserialization
Use loads
and load
Method , You can put a JSON The string is deserialized into a Python object .
loads
Method requires a string parameter , Used to load a string into Python object .
f = open("test.txt", 'r')
# Import json Module into this file
import json
# call loads Method , Convert the string in the file to python object
names = json.loads(f.read())
print(names) # ['zs', 'ls']
print(type(names)) # <class 'list'>
f.close()
load
Method can pass in a file object , Used to load the data in a file object into Python object .
f = open("test.txt", 'r')
# Import json Module into this file
import json
names = json.load(f)
print(names)
print(type(names))
f.close()
The program is running , Because our coding is not standardized , Or other reasons, some objective reasons , As a result, our program cannot continue to run , here ,
The program will have an exception . If we don't handle exceptions , The program may be interrupted directly due to exceptions . In order to ensure the robustness of the program , We
The concept of exception handling is put forward in program design .
When reading a file , If this file does not exist , Will report FileNotFoundError
error .
try...except
Statement can handle the exceptions that may occur during code running . Grammatical structure :
try:
Code blocks where exceptions may occur
except Type of exception :
Processing statement after exception
Example :
try:
f = open("test.txt", 'r')
print(f.read())
except FileNotFoundError:
print(' The document was not found , Please check whether the file name is correct ')
Python Introduction to basic grammar ( One )
First , In the current big dat
Hey, everyone, good duck , Im