Python2 vs Python3
选取几个目前在意的变化
print function
Py3 取消了 print
statement,增加了 print()
function
# py2
print 'a string.'
# py3
print('a string')
print()
定义如下
print(*objects, sep=' ', end='\n', file=sys.stdout)
其中无关键词参数会由 function str()
转换成字符串,由 sep
参数分割,end
参数结束。file
则可以指定输出到的文件对象,要求该对象拥有 write(string)
方法,默认是系统输出。
print('apple', 'pen', sep='-', end='~Ah\n')
# apple-pen~Ah
#
input function
取消 raw_input()
function,增加 input()
function 用法一致。
s = raw_input('-> ')
# -> yeah
Byte-string
bytes
类之前是 str
(的别名?自动转换?),现在是新增的类
class bytes([source[, encoding[, errors]]])
返回不可变的 bytes
对象,字面量如 b'\x80'
。是 bytearray
的不可变版。
可以在第二个参数上指定编码格式
TODO: 这个 errors 参数是什么 .. fallback?
# Python 2
>>> bytes
<type 'str'>
>>> bytes([128])
'[128]'
# Python 3
>>> bytes
<class 'bytes'>
>>> bytes([128])
b'\x80'
>>> bytes('嚯', 'GBK')
b'\xe0\xeb'
>>> bytes('嚯', 'UTF-8')
b'\xe5\x9a\xaf'
# 貌似传一个 int 会返回对应位数的空 bytes 对象
>>> bytes(3)
b'\x00\x00\x00'
Unicode
现在字符串默认是 Unicode,py2 默认是 ASCII,支持 Unicode 则需要 u''
。
# python2
>>> '嚯' == u'嚯'
False
# python3
>>> '嚯' == u'嚯'
True
Division
Py3 的 /
操作符改成了浮点除,新增整除操作符 //
# python2
>>> 6 / 2
3
# python3
>>> 6 / 2
3.0
>>> 6 // 2
3
其他
在编码中继续探索,之后更新进来 ...