首页 > 编程语言 > 详细

Python2 处理 Unicode 字符串的规则

时间:2017-11-16 22:32:21      阅读:223      评论:0      收藏:0      [点我收藏+]

在 Python2 中处理 Unicode 字符串,需遵循如下规则:

1. 程序中的字符串要加前缀 u

2. 不要用 str(),而应该用 unicode() 作为字符串转换函数。不要使用 chr(),而应该使用 unichr()

3. 不要使用 string 模块

4. 如非必要,不要使用 encode 和 decode 编解码 unicode 字符串。只有当要将 unicode 字符串写入文件,数据库,或者网络时,要先将其 encode 为 byte stream,然后再写入,同样的,从文件,数据库,或者网络读取的 byte stream 要先 decode 为 unicode 字符串,然后才能使用。

例如:

if __name__ == ‘__main__‘:

    #str_out = u‘Hello world!‘
    str_out = u‘宁静致远‘
    print ‘>>> str_out = %s‘ % str_out  # for test

    byte_encode = str_out.encode(‘utf-8‘)

    # write the encoded bytes stream into file
    fho = open(‘use_unicode_encode_decode_3.log‘, ‘w‘)
    fho.write(byte_encode)
    fho.close()

    # read the encoded bytes stream from file, and then decode it
    fhi = open(‘use_unicode_encode_decode_3.log‘, ‘r‘)
    byte_in = fhi.read()
    fhi.close()

    str_in = byte_in.decode(‘utf-8‘)
    print ‘<<< str_in = %s‘ % str_in  # for test


完。

 

Python2 处理 Unicode 字符串的规则

原文:http://www.cnblogs.com/gaowengang/p/7846815.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!