您的位置:首页 > 编程语言 > Python开发

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'>
可口可乐
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: