zoukankan      html  css  js  c++  java
  • python2将str类型与unicode类型字符串写入文件的编码问题

    python2将一个字符串写入文件中:

    1、如果字符串是str类型

    # -*- coding:utf-8 -*-
    txtFile="今天天气不错"
    f = open("1.txt", "wb")
    f.write(txtFile)
    f.close()

    2、如果字符串是unicode类型

    # -*- coding:utf-8 -*-
    txtFile=u"今天天气不错"
    txtFile=txtFile.encode('utf-8')  #unicode字符串转换成utf8
    f = open("1.txt", "wb")
    f.write(txtFile)
    f.close()

    #如果不转换,会出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

     NOTE:

    python2 默认编码是ASCII码,使用   # -*- coding:utf-8 -*-    将文件编码为utf-8,即str类型。

    Python3中默认是unicode

    a = u'今天天气不错'             a 是unicode类型
    b = a.encode('utf-8')            b 是str类型                         Unicode --> encode编码 --> GBK/UTF-8
    a = b.decode('utf-8')            a 是unicode类型                 UTF-8 --> decode 解码 --> Unicode

    使用type查看编码形式,unicode是‘unicode’,    gbk和utf-8是‘str或bytes’。

    
    
    
    
     
  • 相关阅读:
    优先队列(堆)
    从CPU管理到进程的引入
    倾听程序员
    数据库设计
    数据库设计之数据库,数据表和字段等的命名总结
    Set容器--HashSet集合
    Java Collection开发技巧
    关于事务
    关于触发器
    windows phone(成语典籍游戏开发)
  • 原文地址:https://www.cnblogs.com/taoyuanming/p/10870739.html
Copyright © 2011-2022 走看看