1.bytes and STR functions
Thanks to this blogger for sharing https://www.cnblogs.com/chownjy/p/6625299.html
Then I'll go over the meaning of his article:
- Bytes format when binary file, all 010101 and so on, and Str is a string type of
- The parameters in the bytes function are bytes (strings, encoding= ' brackets often fill utf-8 ') where encoding must be filled, the STR function is str () and is the same format, for the UTF-8 format for the Universal code format, an English letter a byte, One Chinese character three bytes
- Bytes Data has method decode method, so our previous Read method returns string type data, and Str has method encode type, these two methods can convert these two data types to Utf-8 type
- Python has a strict distinction
bytes
between str
two data types, and you can't bytes
use parameters when you need type parameters str
, and vice versa. This is easily encountered when reading and writing disk files.
Try statement for 2.python
Try A:
B
Except C: #如果发生错误看是否为错误类型C
D
Except E: #如果在try后的语句里发生了异常, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program, and print the default error message)
F
else G; #如果程序未出错则执行G
H
Try A:
B
Finally C: #不管有无发生错误都会执行C语句
D
You can also refer to this blog for more information 23159659
3. WITH...AS structure
This syntax is used instead of the traditional try...finally syntax.
File = open ("/tmp/foo.txt") try: = file.read () finally : file.close ()
Use with...as ... Replace the modified code with the following:
With open ("/tmp/foo.txt") as file: = File.read ()
The following resolves his specific structure:
classSample:
#魔法方法相当于他的属性
def __enter__(self):Print "In __enter__ ()" return "Foo" def __exit__(self, type, value, trace):Print "In __exit__ ()" defget_sample ():returnSample () with Get_sample () as Sample:Print "Sample:", sample
Result is
__enter__ () sample:foo __exit__()
1. The __enter__ () method is executed
2. The value returned by the __enter__ () method-This example is "Foo", assigned to the variable ' sample '
3. Execute code block, print variable "sample" with the value "Foo"
4. The __exit__ () method is called with the real power that it can handle exceptions. You may have noticed that the __exit__ method of the sample class has three parameters-Val, type, and trace. These parameters are quite useful in exception handling.
In the first example, it is equivalent to:
1. Open File
2. Returns the contents of the text
3. Perform a read operation
For more information, please refer to blog http://www.360doc.com/content/16/0905/16/25664332_588595085.shtml
https://www.cnblogs.com/DswCnblog/p/6126588.html
A few confusing points for Python beginners