zoukankan      html  css  js  c++  java
  • Python2 处理 Unicode 字符串的规则

    在 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


    完。

  • 相关阅读:
    attr与prop
    Django框架学习
    库的操作
    javascript 基础知识
    进程
    正则表达式
    模块( collections , time , random , os , sys)
    内置函数
    生成器
    迭代器
  • 原文地址:https://www.cnblogs.com/gaowengang/p/7846815.html
Copyright © 2011-2022 走看看