在python2中主要有str和unicode两种字符串类型,而到python3中改为了bytes和str,并且一个很重要的分别是,在python2中如果字符串是ascii码的话,str和unicode是可以直接进行连接和比较,但是到python3中就不行了,bytes和str是两个独立的类型。另一个重要的是python2中不管是str还是unicode都可以直接写入文件,而不需要加上它是不是str的类型写入方式,但是在python3中如果是写或者读bytes类型就必需带上’b’.
python2类型转换代码如下:
import os
def to_unicode(unicode_or_str):
''' 将str字符串转换为unicode类型
'''
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value
def to_str(unicode_or_str):
''' 将unicode字符串转换为str类型
'''
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode('utf-8')
else:
value = unicode_or_str
return value # Instance of bytes
python3:
import os
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value # Instance of str
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value # Instance of bytes
在python3中直接连接bytes和str类型报错:
print(to_str("test")+to_bytes('test'))
*Traceback (most recent call last):
File “E:\working\project\effective_python\chapter1\bytes_str_unicode.py”, line 22, in
print(to_str(“test”)+to_bytes(‘test’))
TypeError: Can’t convert ‘bytes’ object to str implicitly*
不带’b’写入bytes类型字符串也会报错
with open("C:/tmp.txt", 'w') as f:
f.write(os.urandom(10))
Traceback (most recent call last):
File “E:\working\project\effective_python\chapter1\bytes_str_unicode.py”, line 27, in
f.write(os.urandom(10))
TypeError: must be str, not bytes
而这些问题在python2中不会出现。