zoukankan      html  css  js  c++  java
  • python 学习~unicode 编码

    如果代码文件需要制定编码格式如utf-8:

    1.要在文件开始时写如下注释

    # coding=utf-8 

    2.或则 使用以下代码

    import sys

    reload sys

    sys.setdefaultencoding('utf-8')


    说明:unicode支持不同的编码方式,最著名的的是utf-8.  ASCII字符 的utf-8 编码 与ASCII编码完全一致。

                此外,在程序中不要使用string模块,使用unicode()和unichar()函数代替str()和chr() 函数  

    一般对文件操作、socket操作,需要把内容转换为utf-8,处理完后再转换回来。

    如 以utf-8编码格式 写入文件,  读文件后 可进行解码


    # coding=utf-8
    def  toUTF_8(s):
        if type(s).__name__=='unicode':
            return s.encode('utf-8')
        else:
            return s
        
    def toUnicode(s):
        if type(s).__name__!='unicode':
            return s.decode('utf-8')
        else:
            return s    
    
    CODEC = 'utf-8'
    FILE = 'unicode.txt'
    hello_out = u"世界\n"
    
    bytes_out = toUTF_8(hello_out) 
    f = open(FILE, "w")
    f.write(bytes_out)
    f.close()
    
    
    f = open(FILE, "r")
    bytes_in = f.read()
    f.close()
    hello_in = toUnicode(bytes_in)
    print hello_in
    



  • 相关阅读:
    python 正则表达式
    Python 集合
    Python 类的使用
    Python 分支、循环语句
    Python 基础之字典(dict)的用法
    Python 之字符串常用操作
    python tuple元组操作
    Python list的常用操作
    appium 二次切换webview后无法找到页面元素
    Locust API 文档
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3065362.html
Copyright © 2011-2022 走看看