β

Python 2 to 3 Quick Guide

Ji ZHANG's Blog 46 阅读

Few years ago I was programming Python 2.7, when 3.x was still not an option, because of its backward-incompatibiliy and lack of popular third-party libraries support. But now it’s safe to say Python 3 is totally ready , and here’s a list of references for those (including me) who are adopting Python 3 with a 2.x background.

  1. All Strings Are Unicode
  2. print Becomes a Function
  3. Less Lists More Views
  4. Integer Division Returns Float
  5. Comparison Operators Raises TypeError
  6. Set Literal Support
  7. New String Formatting
  8. Exception Handling
  9. Global Function Changes
  10. Renaming Modules and Relative Import

All Strings Are Unicode

When dealing with non-ASCII encodings in Python 2, there’re str , unicode , u'...' , s.encode() , etc. In Python 3, there’re only text and binary data . The former is str , strings that are always represented in Unicode; the later is bytes , which is just a sequence of byte numbers.

# str to bytes
'str'.encode('UTF-8')
bytes('str', encoding='UTF-8')

# bytes to str
b'bytes'.decode('UTF-8')
str(b'bytes', encoding='UTF-8')

print Becomes a Function

In Python 2, print is a statement, and now it’s used as a function:

print   # Old: print a new line
print() # New

print 'hello', 'world',          # Old: trailing comma suppresses new line
print('hello', 'world', end=' ') # New: end defaults to '\n'

print >>sys.stderr, 'error'     # Old: write to stderr
print('error', file=sys.stderr) # New

print function also provides sep and flush parameters:

print('hello', 'world', sep=',', flush=True)

# Instead of:
print ','.join(('hello', 'world'))
sys.stdout.flush()

Less Lists More Views

A lot of well-known methods now return iterators, or ‘views’, instead of eager-evaluated lists.

k = d.keys(); k.sort() # Old
k = sorted(d.keys())   # New
[x * 2 for x in [1, 2, 3]]
list(map(lambda x: x * 2, [1, 2, 3]))
iter([1]).next()     # Old
iter([1]).__next__() # New
next(iter([1]))      # New

Integer Division Returns Float

print 1 / 2   # Old: prints 0
print 1 / 2.0 # Old: prints 0.5
print(1 / 2)  # New: prints 0.5
print(1 // 2) # New: prints 0

Comparison Operators Raises TypeError

Set Literal Support

s = set([1, 2, 3]) # Old, also valid in Python 3
s = {1, 2, 3}      # New
s = set()          # Empty set
d = {}             # Empty dict

New String Formatting

Python 3 introduces a new form of string formatting, and it’s also back-ported to Python 2.x. The old %s formatting is still available in 3.x, but the new format seems more expressive and powerful.

# by position
'{}, {}, {}'.format('a', 'b', 'c')    # a, b, c
'{2}, {1}, {0}'.format('a', 'b', 'c') # c, b, a

# by name
'Hello, {name}'.format(name='Jerry') # Hello, Jerry

# by attribute
c = 1 - 2j
'real: {0.real}'.format(c) # real: 1.0

# by index
'X: {0[0]}, Y: {0[1]}'.format((1, 2)) # X: 1, Y: 2

# format number
'{:.2f}'.format(1.2)   # 1.20
'{:.2%}'.format(0.012) # 1.20%
'{:,}'.format(1234567) # 1,234,567

# padding
'{:>05}'.format(1) # 00001

Furthermore, Python 3.6 introduces literal string interpolation ( PEP 498 ).

name = 'Jerry'
print(f'Hello, {name}')

Exception Handling

Raise and catch exceptions in a more standard way:

# Old
try:
  raise Exception, 'message'
except Exception, e:
  tb = sys.exc_info()[2]

# New
try:
  raise Exception('message')
except Exception as e:
  tb = e.__traceback__

Global Function Changes

Some global functions are (re)moved to reduce duplication and language cruft.

Renaming Modules and Relative Import

from urllib.request import urlopen, Request
from urllib.parse import urlencode
req = Request('http://shzhangji.com?' + urlencode({'t': 1})
with urlopen(req) as f:
  print(f.read())
from . import somemod
from .somemod import moremod

References

Few years ago I was programming Python 2.7, when 3.x was still not an option, because of its backward-incompatibiliy and lack of popular third-party libraries support. But now it’s safe to say Python 3 is totally ready , and here’s a list of references for those (including me) who are adopting Python 3 with a 2.x background.

  1. All Strings Are Unicode
  2. print Becomes a Function
  3. Less Lists More Views
  4. Integer Division Returns Float
  5. Comparison Operators Raises TypeError
  6. Set Literal Support
  7. New String Formatting
  8. Exception Handling
  9. Global Function Changes
  10. Renaming Modules and Relative Import

All Strings Are Unicode

When dealing with non-ASCII encodings in Python 2, there’re str , unicode , u'...' , s.encode() , etc. In Python 3, there’re only text and binary data . The former is str , strings that are always represented in Unicode; the later is bytes , which is just a sequence of byte numbers.

# str to bytes
'str'.encode('UTF-8')
bytes('str', encoding='UTF-8')

# bytes to str
b'bytes'.decode('UTF-8')
str(b'bytes', encoding='UTF-8')
作者:Ji ZHANG's Blog
原文地址:Python 2 to 3 Quick Guide, 感谢原作者分享。

发表评论