当前位置: 移动技术网 > IT编程>脚本编程>Python > python开发中的编码问题解析

python开发中的编码问题解析

2018年03月27日  | 移动技术网IT编程  | 我要评论

pmma mf001,浏览器自动关闭,两妻时代国语下载

1. 声明

首先声明几个名词解释:
1. 文件本身的编码:可以利用file检查文件的编码格式。例如:

file test.py
test.py: UTF-8 Unicode Java program text

这时文件本身的编码是UTF-8的。

  1. python代码的编码:打开文件,在文件上部添加的encoding。例如:
    # -*- encoding: utf-8 -*-
    import sys
    

    2. 怎么设定编码

    既然存在2个编码,那么就存在相同和不同情况,两者相同自然是没问题,比如都是gb18030或者utf-8,如果不同会怎么样呢?显然是编码显示错误,看如下几个例子:
    文件编码为utf-8,代码编码为gb18030,有:

    # -*- encoding: gb18030 -*-
    
    str_alphabeta = "ABCDEFG"
    print type(str_alphabeta)
    print str_alphabeta
    
    str_kanji = "可口可乐"
    print type(str_kanji)
    print str_kanji
    

    输出为:

    File "test.py", line 1
    SyntaxError: encoding problem: with BOM
    

    出现一个新的关键词BOM,这个可以google一下,如果你在vim中看到这么一个东西,那也是BOM引起的,如果文档是utf-8个人觉得使用无BOM格式会好处理点。
    那么为了能正常运行,需要文档的编码和代码的编码一致

    3. unicode_literals

    来自future库的内容表示现在还在“试用”阶段,如果你追求“新”就用,如果你追求“稳”就别用(我这么理解的,虽然我经常用pision)。
    unicode_literals的帮助是这么写的:

    >>> help(unicode_literals)
    Help on instance of _Feature in module __future__:
    
    class _Feature
     |  Methods defined here:
     |  
     |  __init__(self, optionalRelease, mandatoryRelease, compiler_flag)
     |  
     |  __repr__(self)
     |  
     |  getMandatoryRelease(self)
     |      Return release in which this feature will become mandatory.
     |      
     |      This is a 5-tuple, of the same form as sys.version_info, or, if
     |      the feature was dropped, is None.
     |  
     |  getOptionalRelease(self)
     |      Return first release in which this feature was recognized.
     |      
     |      This is a 5-tuple, of the same form as sys.version_info.
    

    简单地说就是,非unicode(32)的代码编码(例如utf-8),直接赋值一个字符串得到的编码是代码的编码方式,对象的类型是str,但是如果字符串前面加一个“u”就表示这个字符串是unicode(32)的编码,例如:

    # -*- encoding: utf-8 -*-
    
    str_kanji = "可口可乐"
    print type(str_kanji)
    print str_kanji
    
    str_kanji_unicode = u"可口可乐"
    print type(str_kanji_unicode)
    print str_kanji_unicode
    

    输出为:

    
    可口可乐
    
    可口可乐
    

    第一个可口可乐是utf-8编码的(可以通过locale中的LC_CTYPE来验证),第二个是unicode(32)的。
    如果import unicode_literals则变为(代码略):

    
    可口可乐
    
    可口可乐

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网