The difference between Python3 and Python2 (the pit is too long)

Source: Internet
Author: User
Tags chr ord

print function: (Print is a function in Python3, must be enclosed in parentheses ; Python2 print is Class)

The print declaration for Python 2 has been print() replaced by a function, which means we have to wrap the objects we want to print in parentheses.

Python 2

1234 print ' Python ', python_version () print ' Hello, world! ' Print (' Hello, world! ') print "text",; print ' Print more text in the same line '

Run Result:
Python 2.7.6
Hello, world!.
Hello, world!.
Text print more text on the same line

Python 3

1234 Print ('Python ', Python_version ())print (' Hello, world! ') Print ("Some text,", end="") print (' Print more text on the same line ')

Run Result:
Python 3.4.1
Hello, world!.
Some text, print more text in the same line

by input() parsing the user's input: (input from Python3 in the Str;python2 input to the int type, the raw_input of the Python2 get the str type) Unified: Python3 in the use of Input,python2 in Row_input, are entered as STR

Fortunately, the problem of storing user input as an object has been resolved in Python 3 str . In order to avoid the dangerous behavior of reading non-string types in Python 2, we raw_input() have to use instead.

Python 2
Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on Darwin
Type "Help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<type ‘int‘>>>> my_input = raw_input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<type ‘str‘>

Python 3
Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on Darwin
Type "Help", "copyright", "credits" or "license" for more information.

>>> my_input = input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<class ‘str‘>

Division : (Not much impact) (Python3/means true except,% means take-up,//for the floor except for the results); Python2/means the result is based on the divisor dividend the decimal point,//the same as the floor in addition to the unification: Python3/True Division, % means take-up,//result rounding; Python2 with decimal point/true divide,% for remainder,//result rounding

Python 2

12345 print ' Python ', python_version () print ' 3/2 = ', 3/ 2 Print ' 3//2 = ', 3// 2 print ' 3/2.0 = ', 3/ 2.0 Print ' 3//2.0 = ', 3// 2.0

Run Result:
Python 2.7.6
3/2 = 1
3//2 = 1
3/2.0 = 1.5
3//2.0 = 1.0

Python 3

12345 Print ('Python ', Python_version ())print (' 3/2 = ', 3/ 2)print (' 3//2 = ', 3// 2) Print (' 3/2.0 = ', 3/ 2.0)print (' 3//2.0 = ', 3// 2.0)

Run Result:
Python 3.4.1
3/2 = 1.5
3//2 = 1
3/2.0 = 1.5
3//2.0 = 1.0

xrange module:

In Python 3, range() it is implemented like that so that xrange() a specialized xrange() function no longer exists (a named exception is thrown in Python 3 xrange() ).

The xrange() use of creating iterative objects in Python 2 is very popular. For example, for a loop or a list/set/dictionary derivation.
This behaves much like a generator (e.g.. "Lazy evaluation"). But this xrange-iterable is infinite, which means you can traverse infinitely.
Because of its lazy evaluation, if you must not just walk it once, the xrange() function is range() faster (such as for looping). However, it is not recommended that you repeat iterations more than once, because the generator starts from scratch each time.

I want to add ...

http://chenqx.github.io/2014/11/10/Key-differences-between-Python-2-7-x-and-Python-3-x/

Http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html

Python 2.4 vs. Python 3.0

One, the print from the statement into a function

Original: Print 1, 2+3

Instead: Print (1, 2+3)

Two, range and xrange

Original: range (0, 4) result is list [0,1,2,3]

Instead:list (range (0,4))

Original: xrange (0, 4) variable control for the For Loop

Instead:range (0,4)

Three, string

Original: string stored in 8-bit string

Instead: string is stored in 16-bit Unicode string

Iv. changes to the try except statement

Original: try:

......

Except Exception, E:

......

Switch

try:

......

Except Exception as e:

......

V. Open File

Original: file (...)

or open (...)

Switch

only Open (...)

Six, input a string from the keyboard

Original: raw_input ("hint message")

Instead: input ("hint message")

Vii.. Bytes data types

A Bytes Object is an immutable array. The items is 8-bit bytes, represented by integers in the range 0 <= x < 256.

Bytes can be thought of as "byte array" objects, each element is a 8-bit byte, and the value range 0~255.

Since strings are stored in Unicode encoding in Python 3.0, when a binary file is written, the string cannot be written directly (or read) and must be encoded in some way into a sequence of bytes before it can be written.

(a) string encoding (encode) is bytes

Example: s = "Zhang San abc12"

b = s.encode (encoded)

# b is the bytes type of data

# Common encoding methods are: "Uft-16", "Utf-8", "GBK", "gb2312", "ASCII", "latin1" and so on.

# Note: An exception is thrown when a string cannot be encoded as a specified "encoding method"

(ii) bytes decoding (decode) as a string

s = "Zhang San abc12"

b = S.encode ("GBK") # string s encoded as a sequence of bytes in GBK format

S1 = B.decode ("GBK") # decodes byte sequence B into a string in GBK format

# description, an exception is thrown when a sequence of bytes cannot be decoded in the specified encoding format

(iii) Examples of using methods

#coding =GBK

f = open ("C:\\1234.txt", "WB")
s = "Dick and Harry Abcd1234"
# -------------------------------
# in python2.4 we can write this:
# F.write (s)
# but throws an exception in Python 3.0
# -------------------------------
b = S.encode ("GBK")
F.write (b)
F.close ()

Input ("?")

An example of reading this file:

#coding =GBK

f = open ("C:\\1234.txt", "RB")
F.seek (0,2) #定位至文件尾
n = F.tell () #读取文件的字节数
F.seek (0,0) #重新定位至文件开始处
b = F.read (n)
# ------------------------------
# in Python 2.4 b is a string type
# to Python 3.0, B is the bytes type
# Therefore, you need to specify the encoding method to confirm the code
# ------------------------------
s = B.decode ("GBK")
Print (s)
# ------------------------------
# in Python 2.4 You can write print s or print (s)
# to Python 3.0 must write print (s)
# ------------------------------
F.close ()
Input ("?")

Should be displayed after running:

Dick and Harry Abcd1234

(iv) bytes sequence, one but formed, whose contents are immutable

Cases:

S= "ABCD"

B=s.encode ("GBK")

Print B[0] # Display

B[0] = 66

# Execute the sentence, an exception occurred: ' bytes ' object does not the support item assignment

Viii. chr (K) and Ord (c)

Python 2.4.2 before

chr (k) converts the encoded k to characters, the range of K is 0 ~ 255

Ord (c) takes a single character encoding, the range of return values: 0 ~ 255

Python 3.0

chr (k) converts the encoded k to characters, the range of K is 0 ~ 65535

Ord (c) takes a single character encoding, the range of return values: 0 ~ 65535

Nine, division operator

Python 2.4.2 before

10/3 Results of 3

Python 3.0

10/3 results for 3.3333333333333335

//3 results for 3

Ten, byte array object---New

(i) initialization

a = ByteArray (Ten)

# A is an array of 10 bytes, each of which is a byte, and the type borrows an int

# at this point, each element has an initial value of 0

(b) The byte array is mutable

a = ByteArray (Ten)

a[0] =

# You can change its elements with an assignment statement, but the assigned value must be between 0 and 255

(c) A slice of a byte array is still an array of bytes

(iv) Converting a string into a byte array

#coding =GBK

s = "Hello"

b = S.encode ("GBK") # first converts a string into bytes by some sort of "GBK" encoding

C = ByteArray (b) #再将 bytes into a byte array

can also write

C = bytearray ("Hello", "GBK")

(v) byte arrays converted to strings

C = ByteArray (4)

C[0] = 65; c[1]=66; C[2]= 67; C[3]= 68

s = C.decode ("GBK")

Print (s)

# should show: ABCD

(vi) Byte array can be used to write to a text file

#coding =GBK

f = open ("C:\\1234.txt", "WB")
s = "Dick and Harry Abcd1234"
# -------------------------------
# in python2.4 we can write this:
# F.write (s)
# but throws an exception in Python 3.0
# -------------------------------
b = S.encode ("GBK")

F.write (b)
C=bytearray ("Harry", "GBK")
F.write (c)
F.close ()

Input ("?")

Rookiedong's Supplement

1, "Import thread" problem, 2.x module thread in 3.x programming "_thread" (need to be preceded by an underscore). Otherwise, the Importerror:no module named thread will appear.

Dd

The difference between Python3 and Python2 (the pit is too long)

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.