Python 2 Python 3
Python 2 Python 3
import \ L = list(seq)
L = sorted(seq)
import test.support L.sort()
test.test_support
words.sort(
import Tkinter import tkinter words.sort(
lambda x, y:
import \ key=lambda x:
cmp(x.lower(),
urllib.request, \ x.lower())
import urllib y.lower()))
urllib.parse, \
class B(A): class B(A):
urllib.error def __init__(self): def __init__(self):
import \ super(B, self). \ super(). \
import urllib2 urllib.request, \ __init__() __init__()
urllib.error if type(x) == X:
import urlparse import urllib.parse if isinstance(x, X):
if type(x) is X:
import xmlrpclib import xmlrpc.client
while 1: while True:
process() process()
New in Python 3.1 General Notes
Dictionary and set comprehensions; * unpack- Python 3 often returns iterables where Python 2 re-
ing; binary literals; bytes and bytearray types; turned lists. This is usually fine, but if a list is real-
bz2.BZ2File and gzip.GzipFile are context man- ly needed, use the list() factory function. For ex-
agers; collections.Counter dictionary type; ample, given dictionary, d, list(d.keys()) returns
collections.OrderedDict insertion-ordered dictio- its keys as a list. Affected functions and methods
nary type; decimal.Decimals can be created from include dict.items(), dict.keys(), dict.values(),
floats filter(), map(), range(), and zip().
Python 2 Python 3.1 Most of the types module’s types (such as types.
d = {} LongType) have gone. Use the factory function
d = {x: x**3
for x in range(5): instead. For example, replace if isinstance(x,
for x in range(5)}
d[x] = x**3 types.IntType) with if isinstance(x, int).
S = set( Comparisons are strict—x < y will work for com-
S = {x for x in seq}
[x for x in seq]) patible types (e.g., x and y are both numbers or
Python 3.1 both strings); otherwise raises a TypeError.
a, *b = (1, 2, 3) # a==1; b==[2, 3] Some doctests involving floating point num-
bers might break because Python 3.1 uses David
*a, b = (1, 2, 3) # a==[1, 2]; b==3
Gay’s algorithm to show the shortest representa-
a, *b, c = (1, 2, 3, 4) # a==1; b==[2, 3]; c==4
tion that preserves the number’s value. For ex-
x = 0b1001001 # x==73
ample, 1.1 in Python 2 and 3.0 is displayed as
s = bin(97) # s=='0b1100001'
1.1000000000000001, and in Python 3.1 as 1.1.
y = int(s, 2) # y==97
u = "The " # or: u = "The \u20ac"
String Format Specifications
# or: u = "The \N{euro sign}"
v = u.encode("utf8") # v==b'The \xe2\x82\xac' str.format() strings have one or more replace-
w = v.decode("utf8") # w=='The ' ment fields of form: {Name!Conv:Spec}. Name iden-
x = bytes.fromhex("54 68 65 20 E2 82 AC") tifies the object to format. Optional !Conv is: !a
# x==b'The \xe2\x82\xac' (ASCII repr() format), !r (repr() format), or !s
y = x.decode("utf8") # y=='The ' (string format). Optional :Spec is of form:
z = bytearray(y) : Fill Align Sign # 0 Width , .Prec Type
z[-3:] = b"$" # z==bytearray(b'The $') Fill is any character except }. Align is: < (left), >
with bz2.BZ2File(filename) as fh: (right), ^ (center), or = (pad between sign and num-
data = fh.read() ber). Sign is: + (force), - (- if needed), or “ ” (space
counts = collections.Counter("alphabetical") or -). # prefixes ints with 0b, 0o, or 0x. 0 means
# counts.most_common(2)==[('a', 3), ('l', 2)] 0-pad numbers. Width is the minimum width. The
d = collections.OrderedDict( , means use grouping commas. .Prec is the maxi-
(("x", 1), ("k", 2), ("q", 3))) mum width for strs and number of decimal places
# list(d.keys())==['x', 'k', 'q'] for floats. Type is: % (percent), b (binary), d (deci-
dec = decimal.Decimal.from_float(3.75) mal), e or E (exponential), f (float) g or G (general
# dec==Decimal('3.75') float) n (localized) o (octal), x or X (hex). Every-
thing is optional, except that Fill requires Align.
Special Methods "{:*=+10.1f}".format(12345.67) # '+**12345.7'
"{:*>+10.1f}".format(12345.67) # '**+12345.7'
The slice methods (__delslice()__, __get-
"{:+010.1f}".format(12345.67) # '+0012345.7'
slice()__, __setslice__) are gone; instead __del-
"{:,.2f}".format(12345.678) # '12,345.68'
item()__, __getitem()__, and __setitem__ are
called with a slice object. An informIT.com
The methods __hex__() and __oct__() are gone; publication by
use hex() and oct(). To provide an integer, imple- Mark Summerfield.
ment __index__(). #3 Copyright Qtrac Ltd. 2009.
License: Creative Commons Attribution-Share Alike 3.0 U.S.