python3编码声明_python中的编码问题

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中看到这么一个东西,那也是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

输出为:

可口可乐

可口可乐

第一个可口可乐是utf-8编码的(可以通过locale中的LC_CTYPE来验证),第二个是unicode(32)的。

如果import unicode_literals则变为(代码略):

可口可乐

可口可乐

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值