python中的编码问题
2018-03-07 09:59
399 查看
1. 声明
首先声明几个名词解释:1. 文件本身的编码:可以利用
file检查文件的编码格式。例如:
file test.py test.py: UTF-8 Unicode Java program text这时文件本身的编码是UTF-8的。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中看到
<feff>这么一个东西,那也是BOM引起的,如果文档是utf-8个人觉得使用无BOM格式会好处理点。
那么为了能正常运行,需要文档的编码和代码的编码一致。
3. unicode_literals
来自future库的内容表示现在还在“试用”阶段,如果你追求“新”就用,如果你追求“稳”就别用(我这么理解的,虽然我经常用division)。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输出为:
<type 'str'> 可口可乐 <type 'unicode'> 可口可乐第一个可口可乐是utf-8编码的(可以通过locale中的LC_CTYPE来验证),第二个是unicode(32)的。
如果import unicode_literals则变为(代码略):
<type 'unicode'> 可口可乐 <type 'unicode'> 可口可乐
相关文章推荐
- 【python】mysqlDB转xml中的编码问题
- python字符串编码常见问题
- python 编码问题 u'汉字'
- [python]编码问题 待整理
- python中文编码问题(转自http://wolfmaster.iteye.com/blog/638029)
- python写入文件编码问题UnicodeEncodeError
- 玩转Python让人讨厌的编码问题
- Python 中文编码的问题
- python与excel的中文编码问题
- python 编码出错问题
- python的编码问题|encode(编码)decode(解码)
- python编码问题
- 解决Python写入文件编码问题(UnicodeEncodeError: 'ascii' codec can't encode characters in...)
- 菜鸟学Python(4):编码问题
- python基础-字典、enumerate、is和==区别、编码问题、一些有迷惑的方法
- python实战之编码问题:中文!永远的痛
- Python编码问题整理
- python3中的np.load编码问题
- Python 2.7 + SQLite3 编码问题
- python中烦人的编码问题