python2和python3编码区别

在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中不会出现。

参考书籍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值