Python day three: character encoding, file manipulation, functions

Source: Internet
Author: User
Tags define function

Tag: and the Run correlation function returns a Lib object that cannot be interpreted as a value

Review of homework issuesTabular output

The main way to examine the expandtabs of a string is to replace TAB with a space .

Hundred Chicken Hundred Money

Hundred chicken Hundred money is mainly used to make multiple judgments, and then output printing.

Course Content character encodingConcept

Encoding is a format used by computers to store human-readable characters into binary information. Character encoding is primarily for character encoding.

PythonThe relevant methods in

Decode: Decode to convert data from other formats into Unicode format. After conversion is the Bytes type of data. Bytes data characters are converted to bytecode, and ASCII codes are converted to b'meg ' form. The parameters that can be answered are the ones that are decoded using the character encoding.

Encode: encoding that converts data in Unicode encoded format (Bytes form) into other character-encoded formats. The parameters that can be answered are the encoding of what character is used.

The above two methods are used more often in network programming.

Py2and thePyt3the difference between encodings

The string type in Python2 is the Bytes type, and if you do not specify the encoding, running on different platforms may cause garbled behavior.

In Python3 , the string type is utf-8 By default , and if not executed, the string stored in the interpreter is UNICODE by default .

file ProcessingOpen File

There are two ways of opening a file:

1. Create a file object, and then manipulate the file object.

f = open (' Test.txt ')

F.xxx

F.close

Pros and Cons: The advantages are simple and easy to read code, the drawback is that the code is more than the volume, and the structure is not clear.

2. use with to open a file object and then manipulate it in the descendant code.

With open (' B.txt ') as F,open (C.txt) as F1:

F.xxxx

F1.xxxx

Advantages: Less code, clear structure.

Read-only mode and method

If you open a file without specifying how it is opened, the default is to open it using read-only mode. In read-only mode, only the data of the file can be read, and the file cannot be manipulated.

Some common methods:

Seek: moves the cursor to the specified position.

Use example : Seek (Num,pat)

Pat is a pattern with three modes:0: moves the cursor from the beginning of the file. 1: moves the cursor from the current position of the cursor. 2: move the cursor from the end of the file. One of the 0 modes can be any open mode. the 1 and 2 modes must be opened in binary mode.

ReadLines(): reads all the contents of the file into a list of elements, the element is the end of/ n .

ReadLine(): A row of read files.

Read(): Specifies the number of characters to read the contents of the file.

Tell(): Prints where the cursor is currently located. It may be used when a file breakpoint continues to be transmitted.

Insert Patterns and methods

When the file is opened, the parameter ' W ' is appended to the filename, and the default is to open it in insert mode. This mode opens the file, if originally has the file, clears the file content, if originally did not have the file, creates a new file.

Common methods:

Truncate: Cut files, keep only the contents of the file from the beginning to the specified location, all other file contents are emptied.

Write: writes the file and writes the content to the file.

Writelines: writes the file, the transmitted parameter is the list.

Append Patterns and methods

Append mode is to keep the contents of the original file, and then append the file contents to the last file.

Write: writes the file and appends the contents to the file.

Change file

Idea: Change the file, is to create a temporary file, the original file contents of a line of reading, to determine whether it needs to be modified, if necessary to modify. Then write to the temp file. After you have read all of them, write the contents of the temporary file back to the main file.

code example:

Import OS

With open ("Test", encoding= "Utf-8") as F,open (". Test1.swap", ' W ', encoding= "Utf-8") as F1:

For N in F:

If " knife " in N:

n = n.replace (" knife ", " sword " )

F1.write (N)

With open ("Test", ' W ', encoding= "Utf-8") as F, open (". Test1.swap", ' R ', encoding= "Utf-8") as F1:

For N in F1:

F.write (N)

Os.remove (". Test1.swap")

Breakpoint Continuation

idea: In transferring to half of the files, use the Seek(0,2) and tell commands to determine where the cursor is moving and return the value. Then complete the file seek to go there to continue reading values.

code example

With open (' Test ', encoding= "Utf-8") as F,open (' test1 ', ' RB ') as F1:

F1.seek (0,2)

Size = F1.tell ()

F.seek (size)

Print (F.readlines ())

functionConcept

in python , functions fall into two categories, one is built-in, one is a custom function, and a custom function is equivalent to making a tool that calls it the same as using the tool.

When the program code is small, the problem of not using the function is not very large, but when the amount of code goes up. It can be cumbersome to maintain without a function. And the function can make the code feel more structured.

Defining functions

define function words using def, the general definition function to do the following points, the name should be meaningful, easy to read. It is common to add some Chinese comments before writing the function body. Describes the function of the functions, the return value of a class of things.

The format is as follows:

Def fun_name ():

"Test Function"

Print ("Hello World")

Using functions

Use functions: Use defined functions.

There are generally three ways to use a function:

1. Calling functions Directly

calling a function directly is usually the use of calling the parameterless function.

2. Assigning a function return value to a variable

val = foo (), assigns the return value of the function to a variable to use.

3. Place the function as a parameter in another function

Pass the function as a variable to another function.

Max (Max (20,10), 30)

Three -dimensional expression: Place the correct return value on the left side of the if condition is not set and Else is written to The right of the IF.

eg:Print (a) if a>b else print (b)

return value of the function

The function return value is mainly divided into the following situations:

1. return None: function body inside no return,return inside nothing write, direct return to None .

2. returns a single value: The variable or value is immediately followed by a return .

3. return multiple values:return is separated by commas, accept the words to use multiple variables to receive, if you do not want to use this variable and want to save memory space can use _ to receive. Multiple -,-,-,-,-,- can be represented by - * . a,*-,b indicates that only the first return value and the last return value are accepted.

function parameters

The parameters of the function are divided into two types: formal parameter and actual parameter.

It can also be divided into five types according to the form of presentation:

1. Position parameters (mainly for actual parameters):

positional parameters are the parameters that are passed by position when the argument is given to the parameter.

eg

def foo (x, Y, z):

Print (x, y, z)

Foo (+/-)

If the parameters are passed by position, the number must correspond, and the order should correspond. For instance, the above example assigns 1 to x,2 to y, and3 to Z .

2. keyword parameters (mainly for actual arguments)

The key parameter is that the actual parameter can be assigned exactly when it is passed the value to the parameter.

eg

def foo (x, Y, z):

Print (x, y, z)

Foo (z=1,x=3,y=2)

The above example is the x=3,y=2,z=1 assigned to the formal parameters, the number must correspond, but the position can not correspond.

keyword parameters can be mixed with positional parameters, but in the process of delivery, can not be interspersed with, must be positional parameters in front of the keyword parameters after.

3. Default parameter (mainly for formal parameters)

when defining formal parameters, you can define some default values for the parameters, and use them if the arguments do not give him a value.

The default parameters are placed after the other parameters.

4. Indefinite length parameter (mainly for formal parameters)

The main form of an indefinite long parameter is * and **,* is to accept all positional parameters, forming a tuple, assigning the variable to the back. * * is to accept all the keyword parameters, form a dictionary, assign to the variable behind the * *.

eg

def foo (X,y,*args,**kwargs):

Print (Args,kwargs)

5. Named keyword parameters (not commonly used)

After the variable-length parameter is used, it is expected that the variable length parameter has some of its own keyword parameters. In this form

eg:

def foo (x,y,*,sex,heigh):

Print (X,y,sex,heigh)

this way, if you don't use keyword parameters to transfer sex and heigh , you will get an error.

Python day three: character encoding, file manipulation, functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.