python 中字符编码

背景:在跑hadoop是python脚本经常要处理不同的格式的编码数据,主要字符编码:ascii,gb18030,unicode,utf-8等

python有两种字符串

byteString = "hello world! (in my default locale)"

unicodeString = u"hello Unicode world!"

相互转换

1 s = "hello normal string"

2 u = unicode( s, "utf-8" )

3 backToBytes = u.encode( "utf-8" )

3 backToUtf8 = backToBytes.decode(‘utf-8’) #与第二行效果相同

如何判断

if isinstance( s, str ): # 对Unicode strings,这个判断结果为False

if isinstance( s, unicode): # 对Unicode strings,这个判断结果为True

if isinstance( s, basestring ): # 对两种字符串,返回都为True

系统默认编码

import sys

sys.getdefaultecoding() "default ascii" 默认是字节编码

decode,encode 使用

  python 系统内部处理是unicode 编码,在转码时,首先将不同编码格式的字符串转化为unicode, 如:s="中国",s.decode('gbk')。对unicode内码的数据用encoding转成相关编码的字符数据。s.encode('utf8').

-*- coding: utf-8 -*-
PY文件当中是不支持中文的,即使你输入的注释是中文也不行,为了解决这个问题,就需要把文件编码类型改为UTF-8的类型,输入这个代码就可以让PY源文件里面有中文了。
python 解码 unicode 明文
s = '\u4f60\u597d\uff0c\u4ece\u6ce2\uff01'

1. u = eval('u"' + s + '"')

2.u = s.decode('unicode_escape')

3.使用 python3 

原文地址:https://www.cnblogs.com/kangyoung/p/2946567.html