The core changes brought by the Python3.1 version

Source: Internet
Author: User
Here we will analyze the changes to the Python 3.1 core language, including formatting, specifiers, and other aspects of the string. Hopefully these changes will help you understand Python 3.1.

Seven months after Python 3.0 was released, the Python core developer released a new version of Python 3.1 on June 27, 2009. Although this 3.1 version is only a small upgrade to Python 3.0, it not only brings many interesting features to developers, but also improves performance. This article will give the reader a detailed description of the changes in the core language, standard libraries, and performance improvements for Python version 3.1.

First, the formatting of the string

The latest version of Python brings us to the auto-fill function of the pleasing format field. We know that many programs often need to format strings. The Python 2.x version uses a percent-semicolon operator similar to the [s]printf function, as follows:

  

' Hello, world! ' Python 3.0 adds a more advanced string formatting feature, as follows:

  

' Hello, world! ' Today, Python 3.1 has a new improvement in string formatting. For Python 3.0来, you must give the index of each positional parameter whenever you want to refer to the positional parameter in the format string. But in Python 3.1, you can put these indexes behind your head, because Python fills in the parameters for you in turn:

  >>> ' {}, {}! '. Format (' Hello ', ' World ')   

Second, PEP-378: format specifier for thousand separators

In a financial application, you typically use thousands separators in numbers. People who work in finance or accounting do not write "You owe me $12345678", but "you owe me $12,345,678" and they wont use commas as separators. So how do you use Python to achieve this effect:

  

' 12,345,678 ' You can group numbers with other delimiters. The width specifier here (8) includes a comma and a decimal point:

  

The ' 12,345.7 ' comma is usually used as the default separator character, and if you want to use a different character as the separator character, simply replace the comma with your preferred character by using the Replace function, as shown here:

  

' 1_234 ' Of course, you can also use the Format function as a string method:

>>> ' {0:8,.1f} '. Format (123.456)

Three, Maketrans function

Using the Maketrans () and translate () functions, we can use a set of characters to replace another set. This substitution function is somewhat cumbersome because it requires the use of the Maketrans () function (the function is to map the input character to the output character) to create a conversion table, and then pass the conversion table to the translate () function. Of course, the string module still has its own maketrans () function, but Python 3.1 does not favor using it, but rather appreciates the use of a separate Maketrans () function to manipulate bytes, byte arrays, and strings.

The following example shows how to use the Maketrans () and translate () functions to handle byte objects. It is important to note that the conversion table for bytes has 256 table entries (each of which corresponds to one possible byte), and this example maps most of the bytes to themselves, with only 1, 2, and 3 exceptions, because they map to 4,5 and 6, respectively. As shown below:

  >>> TT = Bytes.maketrans (b ' 123 ', B ' 456 ')   >>> len (TT)   up   >>> tt   B ' \x00\ x01\x02\x03\x04\x05\x06\x07\x08\   t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\   x14\x15\x16\x17\x18\x19\x1a\ x1b\x1c\x1d\   x1e\x1f! " #$%&\ ' () *+,-./0456456789:;<=>   ? @ABCDEFGHIJKLMNOPQRSTUVWXYZ [\\]^_ ' ABCD   efghijklmnopqrstuvwxyz {|} ~\x7f\x80\x81\   x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\   x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\   x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\   xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\   xaa\xab\xac\ xad\xae\xaf\xb0\xb1\xb2\xb3\   xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\   xbe\xbf\xc0\xc1\xc2\xc3\xc4\ Xc5\xc6\xc7\   xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\   xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\   Xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\   xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\   xf0\xf1\xf2\xf3\ Xf4\xf5\xf6\xf7\xf8\xf9\   

After the conversion table is built, we simply pass it to the translate () function, as follows:

  

B ' 456456 ' We can also pass other parameters as the characters to be removed:

  

B ' 45646 ' we can see that the original 5 has been deleted from 123456, but the conversion gets 5 (remember, our mapping table converts 2 to 5) and did not delete it. This means that the system is the first to remove the corresponding characters from the original string before the conversion operation.
The conversion of a string is slightly different, and the string version of the Maketrans function returns a dictionary:

  >>> TT = Str.maketrans (' 123 ', ' 456 ')   {49:52, 50:53, 51:54}   >>> ' 123456 '. Translate (TT)   

Iv. Changes related to mathematics

  >>> int.bit_length (5)      

The 3.1 version has also changed in terms of mathematics.

int adds a bit_length method

In the new version, the int variable has a bit_length method that returns the number of bits of the int variable when it is represented by a binary number. For example, the binary representation of the number 19 is 10011, then the number of bits is 5:

Rounding of ' 0b10011 ' floating-point numbers

The Python 3.0 and the previous round () function are a bit capricious: if you don't specify precision, it returns an integer, and if you specify precision, it returns the type of data you entered:

  >>> round (+)   >>> Round (1000.0) +   >>> round (2)   1000   

1000.0 in Python 3.1, as long as the number entered is an integer (even if it is represented in the form of a floating-point number, such as 1000.0), it always returns an integer:

  >>> round (+)   >>> round (1000.0)   >>> round (2)   1000   

1000 representation of floating-point numbers

Currently, real numbers are represented in most hardware and operating systems in 32-bit (single-precision) or 64-bit (double-precision). However, this can cause some real numbers to not be accurately represented. Because of the binary nature of computer memory, some numbers use decimal notation to be very concise, but if you use a floating point scheme, it will be complicated. For example, with a 32-bit single-precision floating-point number representing the digit 0.6, it is 0.59999999999999998:

>>> 0.6

0.59999999999999998 for this presentation, the numbers above are intended to be as accurate as possible, but are unfriendly to the user. Python 3.1 uses a new algorithm to make the representation of the original value as concise as possible. So in Python 3.1, people enter the numbers above, a more concise representation:

>>> 0.6

0.6 this is very precise, unless you encounter arithmetic operations. For example, the value of the expression 0.7+0.1 is expressed in 32-bit floating-point notation, it is 0.79999999999999993, and the value of the number 0.8 is expressed in 32-bit floating-point numbers, which is 0.80000000000000004. This means that 0.7+0.1 is not equal to 0.8, which can lead to some problems. For example, the following loops will never be resting:

  >>> x = 0.0   >>> while X! = 1.0:   ... print (repr (x)) ...   x + = 0.1 output results:   0   0.100000000 00000001   0.20000000000000001   0.30000000000000004   0.40000000000000002   0.5   0.59999999999999998   0.69999999999999996   0.79999999999999993   0.89999999999999991   0.99999999999999989   1.0999999999999999   1.2   1.3   1.4000000000000001   1.5000000000000002   

... In Python 3.0, the repr () function returns the actual representation, whereas in Python 3.1 it returns a concise representation. Whether in Python 3.0 or Python 3.1, the print () function shows a concise representation:

  >>> Print (0.1)   0.1   

The 0.1Python language also has a module called decimal, which can be used for precise representation of real numbers. It uses a different representation scheme to represent floating-point numbers and, in the case of memory runs, uses as many digits as possible to represent a real number-and there is no rounding error when doing arithmetic. In Python 3.0, the decimal type uses a new method to initialize the value it represents from a string, and in Python 3.1 adds another new method, From_float (), to receive the floating-point number. Note that even when using from_float (), the decimal module is more accurate than 32 bits.

  >>> from decimal import decimal   >>> decimal.from_float (0.1)   

V. Improved with statements

In Python 2.5, the With statement was introduced as a __future__ feature, and the formal introduction of the statement was actually started in Python 3.0. In Python version 3.1, the statement has been able to support more resources. The most common scenario is that it can open input, output files, and close them after processing is complete. In Python 3.0, we either use nested with statements or explicitly close them in a file. Here is an example of Python 3.0, which opens an input file, reads its contents as a string, processes the contents with the title () method of the string, and writes the results to an output file.
This example contains two nested with statements, noting the last line in the nested with statement. When the code tries to read the OUT.txt, the result is empty because the file is buffered and has not been written. When this with statement is complete, Python closes the file, so the last line of code will determine that the contents of the OUT.txt are indeed uppercase text.

  Open (' In.txt ', ' W '). Write (' abc def ') with   open (' In.txt ') as In_file:   with open (' OUT.txt ', ' W ') as Out_file:   text = In_file.read ()   assert text = = ' abc def '   text = Text.title ()   assert text = = ' abc def '   Out_file. Write (text)   

Assert open (' OUT.txt '). Read () = = ' ABC Def ' see nested with statement, is not feeling a little headache, hehe. Next, we'll open two two files and close them after processing is done (if you need to open three files, you need three nested with statements). Python 3.1 runs you open all files with a single with statement:

  Open (' In.txt ', ' W '). Write (' abc def ') with   open (' In.txt ') as In_file:   with open (' OUT.txt ', ' W ') as Out_file:   text = In_file.read ()   assert text = = ' abc def '   text = Text.title ()   assert text = = ' abc def '   Out_file. Write (text)   assert open (' OUT.txt '). Read () = = "   

Another improvement in Python 3.1 is gzip. Gzipfile and Bz2.bz2file can now also be used with the WITH statement. We know that these are compressed file formats. The following example code uses the gzip file and the bz2 file to store 5,000-byte content and displays its dimensions. There are also some additional Python 3 features, such as statistical results with named attributes and advanced string formatting.

  From bz2 import bz2file from   gzip import gzipfile   import os with   gzipfile (' 1.gz ', ' WB ') as G, Bz2file (' 1.bz2 ', ' WB ') as B:   g.write (b ' x ' * b.write)   for ext in ('. Gz ', '. bz2 '):   filename = ' 1 ' + Ext
  print (' the size of the {0} file is {1.st_size} bytes '. Format (ext, os.stat (filename)) output: The size of the   . GZ fil E is bytes   

Vi. Summary

Seven months after Python 3.0 was released, the Python core developer released a new version of Python 3.1 on June 27, 2009. Although this 3.1 version is only a small upgrade to Python 3.0, it not only brings many interesting features to developers, but also improves performance. This article gives the reader a detailed description of the changes in the core language of the Python version 3.1, and in the following article we will continue to introduce the changes in the standard library and performance improvements for the new version.

  • Related Article

    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.