One, character encoding
Character encoding: translates human characters into numbers that a computer can recognize.
Character encoding table: a table of characters that correspond to numbers.
For example: ASCII, GBK, Utf-8, Unicode
Unicode----> Encode (' utf-8 ')----> bytes
Bytes----> decode (' utf-8 ')----> Unicode
The string in Python3 is divided into 2 types:
x= ' AA '#存成unicode
Y=x.encode (' Utf-8 ')#此时转存成bytes
Unicode and bytes#python3默认是unicode
The string in Python2 is also divided into 2 types:
X=u ' AA '#与python3的字符串概念一样
y= ' BB '#与pyhton3的bytes一样.
Unicode and bytes
Python3 The default format is Unicode
In a word: What format is the character encoded, and what format will it be decoded.
Second, the operation of the file
1, R read mode, the file does not exist when the file is not created.
f = open (' A.txt ', ' R ', encoding= ' utf-8 ')
Print (F.read ())
1.1 b Mode:#此时不在需要制定编码格式
f = open (' A.txt ', ' BR ')
Print (F.read ())
F.close ()
#指定字符解码
f = open (' a.txt ', ' RB ')
Print (F.read (). Decode (' Utf-8 '))
F.close ()
1, w write mode, file exists empty file, does not exist create file.
f = open (' A.txt ', ' W ')
F.write (' 111 ')
F.close ()
1.1. Whether writeable can be written
f = open (' A.txt ', ' W ')
F.write (' 111 ')
Print (F.writable ())
F.close ()
1.2. Write a line:
f = open (' A.txt ', ' W ')
F.writelines (' 1111\n22222222222 ')
F.close ()
1.3, a append mode, the file does not exist to create, the file exists jumps to the end of the file.
f = open (' A.txt ', ' a ')
F.writelines (' 111a1\n22222222222 ')
F.close ()
1.3.1, viewing the cursor position of a file
f = open (' A.txt ', ' a ')
F.writelines (' 111a1\n22222222222 ')
Print (F.tell ())#打印光标的位置, append the general cursor to the end.
F.close ()
#打开文件就会跳到文件的结尾处, files are created when the file does not exist.
Summarize:
File operation mode: Read can only read can not append and write, write can only write can not read and append, append also only append, but this is the default situation, if you need to read at the time of writing or write when reading, please use the permission a+,r+,w+
File operation method: Only W and a file will be created if the file does not exist.
1.4 RB mode, direct read bytes mode.
f = open (' a.txt ', ' RB ')
Print (F.read ())
1.4.1 WB mode, direct write B mode, but the default is not directly written, need to encode.
f = open (' A.txt ', ' WB ')
F.write (' aaaaa '. Encode (' Utf-8 '))
1.4.2 AB mode needs to be added encode
It is important to note that the F.close () operation that we perform after the end of the file operation is actually closing the file at the operating system level, but the F = open () variable defined in the program still exists. Only the DEL variable, the variable is cleared. This means that the file is closed, but the method still exists, and the method cannot execute!!!!
1.4. cpoy files using RB and WB
Import Sys
If Len (SYS.ARGV) < 3:
Print (' Insufficient parameters! ')
Elif len (SYS.ARGV) > 3:
Print (' parameter wrong! ')
Else
With open (R '%s '%sys.argv[1], ' RB ') as Read_f,open (R '%s '%sys.argv[2], ' WB ') as Write_f:
For line in Read_f:
Write_f.write (line)
#使用rb模式就不在需要考虑编码的问题了.
1.5 Other actions for files: file operation read () is read by default and read by default, one character at a time.
F =open (' a.txt ', ' R ')
Print (F.read ())
F =open (' a.txt ', ' RB ')
Print (F.read (3). Decode (' Utf-8 '))
#一个中文汉字占3个字符位, if the number of characters in the read process is not a multiple of 3, will be an error, the default is read in bytes.
Seek () controls the position of the cursor. The default is a reference to the beginning of the file.
0 represents the beginning, 1 represents the current position, and 2 represents the end of the file.
Hello, xiaoming.
f = open (' A.txt ', ' R ', encoding= ' utf-8 ')
Print (F.read (1))
Print (F.tell ())
F.seek (6)
Print (F.read (1))
You
3
Ah
f = open (' a.txt ', ' RB ')
Print (F.read (3). Decode (' Utf-8 '))
Print (F.tell ())
F.seek (6,0)
Print (F.read (3). Decode (' Utf-8 '))
You
3
Ah
f = open (' a.txt ', ' RB ')
Print (F.read (3))
Print (F.tell ())
F.seek (3,1)
Print (F.tell ())
Print (F.read (). Decode (' Utf-8 '))
B ' \xe4\xbd\xa0 '
3
6
Ah, Xiaominghehe.
Seek has a pattern of 3. 0 1 2
1 and 2 modes must be run in B mode
0 mode starts with a file
1 mode is based on the current cursor
#模拟tailf command
Import time
Import Sys
With open (R '%s '%sys.argv[2], ' RB ') as F:
F.seek (0,2)
While True:
line = F.readline ()
If line:
Print (Line.decode (' Utf-8 '), end= ")
Else
Time.sleep (0.3)
1.6 Truncate intercept characters
Hello, xiaoming.
With open (' a.txt ', ' r+ ', encoding= ' utf-8 ') as F:
F.truncate (9)
Oh, hello.
#但是如果截取的字符少了, there will be garbled cases
If the file is empty, it is intercepted as a space.
Third, function
With the more functions of the program, the complexity of the code becomes larger, the organization structure is not clear, and the readability is poor.
The code is poorly redundant and extensible. A tool is a function, a call to use.
1, the Classification of functions:
1. Built-in functions
Len () print () max () ...
2. Custom Functions
2, the use of functions:
1. Define function {Define function just check syntax, do not execute code}
2. In the Call function
The definition of a function is similar to the definition of a variable, without defining the variable beforehand and referring to the variable directly, an error is given.
Calling a function without defining a function beforehand is equivalent to referencing a non-existent variable name.
3, the definition of functions:
def function name (ARG1,ARG2,ARG3):
"' Notes '
function body
The return value does not have a type limit, return can have more than one, but only once, and returns the result after return. No return returns none.
The parameter function requires a return value, and the parameterless function generally does not require a return value.
The invocation of a function can be used as a parameter to other functions.
Function name: usually verb, annotation information must have
Parameters....
4. Define the three forms of the function:
1, no parameter function: only to perform some operations, such as user interaction, printing.
2, has the parameter function: needs the external pass in the argument, can execute the related logic.
3, empty function: Design the structure of the code.
5. The parameters of the function are divided into the actual parameter and the formal parameter.
Actual attendance takes up memory space, and parameters do not occupy memory space.
A parameter is a variable name: An argument is a variable value.
The function does not bind the parameter until the call phase argument.
6, the classification of parameters;
1. Positional parameters: The positions are defined sequentially in order from left to right.
Positional parameters: Defining variables
Positional arguments: Corresponds to formal parameter one by one
Syntax: A positional argument must precede a keyword argument.
The same parameter cannot pass multiple values.
2. Keyword arguments: Name the value, Name=value
3, the default parameter: In the definition phase has been assigned to the parameter, meaning that in the call phase can not pass the value.
def foo (x,y=11111):
Print (x)
Print (y)
Foo (1, ' a ')
The default parameter must be placed after the position parameter. The default parameter is assigned only once, and only once, in the definition phase.
The value of the default parameter should be defined as an immutable type. ****
7, variable length parameter refers to the number of actual arguments is not fixed.
The actual parameter is divided into 2 kinds of positional real participation keyword arguments.
The formal parameter must have 2 mechanisms to handle the overflow of arguments defined by location separately: *
An overflow of arguments defined by a keyword * *
Overflow parameters are processed by position, and these overflow parameters are assigned to args
If no overflow occurs, args returns an empty tuple.
def foo (X,y,*args):
Print (x)
Print (y)
Print (args)
Foo (1,2,3,4,5,6,7)
def foo (X,y,**kwargs):
Print (x)
Print (y)
Print (args)
Foo (x=1,y=2,z=3)
1
2
{' Z ': 3}
#关键字溢出会将溢出的参数放到一个字典中保存.
* Represents positional parameters,
The parameters defined after the * are the key arguments, and must be passed as key glyph parameter.
* The following parameters must be passed to the keyword.
def foo (name,age,*,sex= ' Male ', group):
Print (name)
Print (age)
Print (Sex)
Print (group)
Foo (' Zs ', 111,group= ' SC ', sex= ' male ')
Zs
111
Male
Sc
*agrs and **kwargs are used in the joint.
def foo (name,age=100,*args,sex= ' male ', Group,**kwargs):
* * Represents the keyword parameter
A parameter cannot be assigned a value of 2 times.!!
*args extension methods:
def foo (X,y,*args):
Print (x)
Print (y)
Print (args)
Foo (1,5,* (1,3,4,5))
1
5
(1, 3, 4, 5)
def foo (x, y):
Print (x)
Print (y)
Print (args)
Foo (* (4,5))
4
5
A function is an object of the first class: refers to a function that can be passed as data.
Functions can be returned as functions, and can be used as elements of a container type.
Exercise 1, write the function, the user passed in the modified file name, with the content to be modified, execute the function, completed batch modification operation
Law 1,
Import OS
def file (File,key,new_key):
With open (R '%s '%file, ' r ', encoding= ' Utf-8 ') as File_r,open ('. File ', ' W ', encoding= ' Utf-8 ') as File_w:
For line in File_r:
File_w.write (Line.replace (Key,new_key))
Os.remove (file)
Os.rename ('. file ', file)
File (' db ', ' xiaoming ', ' DSB ')
Law 2,
Import Re,os
def file (file,key,key_new):
File_open = open (R '%s '%file, ' r ', encoding= ' utf-8 ')
W_str = ' '
For line in File_open:
If Re.search (key,line):
line = Re.sub (key,key_new,line)
W_str+=line
Else
W_str+=line
File_new_open = Open ('. File ', ' W ', encoding= ' utf-8 ')
File_new_open.write (W_STR)
File_open.close ()
File_new_open.close ()
Os.remove (file)
Os.rename ('. file ', file)
File (' db ', ' DSB ', ' xiaoming ')
Method 3,
Import Re,os
def file (file,key,key_new):
File_open = open (R '%s '%file, ' r ', encoding= ' utf-8 ')
W_str = ' '
For line in File_open:
If Re.search (key,line):
line = Re.sub (key,key_new,line)
W_str+=line
Else
W_str+=line
File_new_open = Open ('. File ', ' W ', encoding= ' utf-8 ')
File_new_open.write (W_STR)
File_open.close ()
File_new_open.close ()
Os.remove (file)
Os.rename ('. file ', file)
Return ' Acessfull '
def foo (a,b,c):
Print (a)
Print (b)
Print (c)
Return file (a,b,c)
res = foo (' db ', ' xiaoming ', ' DSB ')
Print (RES)
Results:
Db
Xiao ming
Dsb
Acessfull
@ Supplemental Python formatted string
Format Description
Percent percentile sign #就是输出一个%
%c character and its ASCII code
%s String
%d signed integer (decimal)
%u unsigned integer (decimal)
%o unsigned integer (octal)
%x unsigned integer (hexadecimal)
%x unsigned integer (16 uppercase characters)
%e Floating-point numbers (scientific notation)
%E Floating point number (scientific notation, E instead of e)
%f floating point number (with decimal point symbol)
%g Floating-point numbers (%e or%f depending on the size of the value)
%G Floating-point number (similar to%G)
%p pointer (memory address with hexadecimal print value)
%n The number of stored output characters into the next variable in the parameter list
The% format character can also be used in dictionaries, and the output can be formatted by using% (name) to refer to the elements in the dictionary.
The minus sign indicates that the number should be left-aligned, and "0" tells Python to fill the number with a leading 0, plus the number always displays its positive and negative (+,-) symbol, even if the number is positive.
You can specify the minimum field width, for example: "%5d"% 2. A period character can also be used to specify additional precision, such as "%.3d"% 3.
e.g.
# example: Numeric formatting
nyear = 2018
Nmonth = 8
Nday = 18
# formatted date%02d number to two-bit integer vacancy fill 0
print '%04d-%02d-%02d '% (nyear,nmonth,nday)
>> 2018-08-18# Output results
Fvalue = 8.123
print '%06.2f '%fvalue# reserved 2-bit decimal floating-point with a width of 6
>> 008.12# Output
print '%d '%10# Output Decimal
>> 10
print '%o '%10# output octal
>> 12
print '%02x '%10# output two-bit hex, letter lowercase blank complement 0
>> 0a
print '%04x '%10# output four-bit hex, letter capital Vacancy 0
>> 000A
print '%.2e '%1.2888# Output floating-point type with scientific notation reserved 2 decimal places
>> 1.29e+00
Formatting operator Auxiliary directives
Symbolic effect
* Define width or decimal point accuracy
-Used for left alignment
+ Show plus sign (+) in front of positive number
<sp> show spaces in front of positive numbers
# 0 (' 0 ') is displayed in front of the octal number, preceded by ' 0x ' or ' 0X ' in hexadecimal (depending on
Using ' x ' or ' x ')
0 The number shown is preceded by ' 0 ' instead of the default space
% ' percent ' output a single '% '
(VAR) mapping variable (dictionary parameter)
M.N m is the smallest total width displayed, and n is the number of digits after the decimal point (if available)
Here are some examples of using format strings:
Hex Output:
>>> "%x"% 108
' 6c '
>>>
>>> "%x"% 108
' 6C '
>>>
>>> "% #X"% 108
' 0x6c '
>>>
>>> "% #x"% 108
' 0x6c '
Floating-point number and scientific notation output:
>>>
>>> '%f '% 1234.567890
' 1234.567890 '
>>>
>>> '%.2f '% 1234.567890
' 1234.57 '
>>>
>>> '%E '% 1234.567890
' 1.234568E+03 '
>>>
>>> '%e '% 1234.567890
' 1.234568e+03 '
>>>
>>> '%g '% 1234.567890
' 1234.57 '
>>>
>>> '%G '% 1234.567890
' 1234.57 '
>>>
>>> "%e"% (1111111111111111111111L)
' 1.111111e+21 '
Integer and string output:
>>> "%+d"% 4
' +4 '
>>>
>>> "%+d"%-4
'-4 '
>>>
>>> "We are at%d%%"% 100
' We is at 100% '
>>>
>>> ' Your host is:%s '% ' Earth '
' Your host Is:earth '
>>>
>>> ' Host:%s/tport:%d '% (' Mars ', 80)
' Host:mars port:80 '
>>>
>>> num = 123
>>> ' Dec:%d/oct:% #o/hex:% #X '% (num, num, num)
' dec:123/oct:0173/hex:0x7b '
>>>
>>> "mm/dd/yy =%02d/%02d/%d"% (2, 15, 67)
' Mm/dd/yy = 02/15/67 '
>>>
>>> W, p = ' Web ', ' page '
>>> ' http://xxx.yyy.zzz/%s/%s.html '% (W, p)
' Http://xxx.yyy.zzz/Web/page.html '
This article from "Man should self-reliance" blog, please be sure to keep this source http://nrgzq.blog.51cto.com/11885040/1949608
Python the third day