美文网首页Python
Python中的编码

Python中的编码

作者: SnailTyan | 来源:发表于2017-09-07 16:49 被阅读22次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    Python处理字符串,写文件时会碰到许多的编码问题,特别是涉及到中文的时候,非常烦人,但又不得不学。下面主要记录工作过程中碰到的Python编码问题。

    1. 字符串编码

    Python的字符串类型为str,可以通过type函数查看返回的类型。Python中字符串默认的编码方式需要通过sys.getfilesystemencoding()查看,通常是utf-8u'中文'构造出来的是unicode类型,不是str类型。

    # 查看字符串编码方式
    >>> import sys
    >>> print sys.getfilesystemencoding()
    utf-8
    
    >>> s1 = '中国'
    >>> s2 = u'中国'
    >>> type(s1)
    <type 'str'>
    >>> type(s2)
    <type 'unicode'>
    

    str类型和unicode类型分别有decodeencode函数。str.decode用来将str转为unicodeunicode.encode用来将unicdoe转为str。用法如下:

    # decode
    >>> s1.decode('utf8')
    u'\u4e2d\u56fd'
    >>> type(s1.decode('utf8'))
    <type 'unicode'>
    
    # encode
    >>> s2.encode('utf8')
    '\xe4\xb8\xad\xe5\x9b\xbd'
    >>> type(s2.encode('utf8'))
    <type 'str'>
    
    

    2. 代码文件编码

    py文件默认的编码是ASCII编码,中文显示时会进行ASCII编码到系统默认编码的转换,在运行Python文件时经常会报错。因此需要设置py文件的编码为utf-8。设置方式如下:

    # _*_ coding: utf-8 _*_
    

    相关文章

      网友评论

      本文标题:Python中的编码

      本文链接:https://www.haomeiwen.com/subject/orwijxtx.html