编码

#python3中的字符串是unicode字符串而不是字节数组。这是与python2相比最大的差别
#在python2中,我们需要区分普通的以字节为单位的字符串以及unicode字符串

import unicodedata

def unicode_test(value):
    name = unicodedata.name(value) #接受一个unicode字符,返回大写形式的名称
    value2 = unicodedata.lookup(name) #接受不区分大小写的标准名称,返回一个unicode字符
    print('value="%s", name="%s", value2="%s"' % (value, name, value2))

unicode_test('A') #value="A", name="LATIN CAPITAL LETTER A", value2="A"
unicode_test('u00a2') #value="¢", name="CENT SIGN", value2="¢"
unicode_test('') #value="中", name="CJK UNIFIED IDEOGRAPH-4E2D", value2="中"
unicode_test('u00e9') #value="é", name="LATIN SMALL LETTER E WITH ACUTE", value2="é"
print('cafu00e9') #café
print('cafN{LATIN SMALL LETTER E WITH ACUTE}') #café

编码

#将字符串转化为一系列字节的过程
snowman = 'u2603'
print(len(snowman)) #1
ds = snowman.encode('utf-8')
print(ds) #b'xe2x98x83'
print(len(ds)) #3
print(type(ds)) #<class 'bytes'>
print(type(snowman)) #<class 'str'>

解码

#将字节序列转化为unicode字符串的过程
#我们从外界文本源(文件、数据库、网站、网络API等)获得的所有文本都是经过编码的字节串
#重要的是需要知道它是以何种方式编码的,这要才能逆转编码过程以获得unicode字符串
print(ds.decode('utf-8')) #
原文地址:https://www.cnblogs.com/jzm17173/p/5766611.html