Effective Python 读书笔记: 3 了解bytes、str与unicode的区别

# -*- encoding: utf-8 -*-

import sys

'''

第3条: 了解bytes、str与unicode的区别

关键:
1 字符序列
python2:
str: 二进制序列
unicode: unicode序列
str转unicode: 用decode('utf-8'),从二进制解码为正常字符串
unicode转: 用encode('utf-8'),将正常字符串编码为二进制序列

python3:
bytes: 二进制序列
str: unicode序列
bytes转str: 用decode('utf-8'),从二进制解码为正常字符串
str转bytes: 用encode('utf-8'),将正常字符串编码为二进制序列

2 向文件中读写二进制数据应该用rb或wb
python3中 写入文件用with open('xx.txt', 'wb') as f:
不要用with open('xx.txt', 'w') as f:
这样可以解决python3无法向文件中写入二进制内容的问题
rb同理。

3 对输入数据操作之前,使用辅助函数保证字符序列的类型是期望类型

参考:
Effectiv Python 编写高质量Python代码的59个有效方法

'''

def to_str(strOrUnicode):
    if isinstance(strOrUnicode, unicode):
        strOrUnicode = strOrUnicode.encode('utf-8')
    return strOrUnicode


def to_unicode(strOrUnicode):
    if isinstance(strOrUnicode, str):
        strOrUnicode = strOrUnicode.decode('utf-8')
    return strOrUnicode


def process():
    value = "hello world"
    print type(value)
    result = to_str(value)
    print result
    print type(result)
    print "###### \n"

    value = u"hello world"
    print type(value)
    result = to_str(value)
    print result
    print type(result)
    print "###### \n"

    value = "hello world"
    print type(value)
    result = to_unicode(value)
    print result
    print type(result)
    print "###### \n"

    value = u"hello world"
    print type(value)
    result = to_unicode(value)
    print result
    print type(result)


if __name__ == "__main__":
    process()

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/88583932