很高兴知道:
您在谈论两种类型的字符串,字节字符串和 unicode 字符串。每个都有将其转换为其他类型字符串的方法。 Unicode 字符串有一个产生字节的 .encode() 方法,而字节字符串有一个产生 unicode 的 .decode() 方法。意思是:
unicode.enocde() ----> 字节
和
bytes.decode() -----> unicode
而 UTF-8 无疑是最流行的 Unicode 存储和传输编码。它为每个代码点使用可变数量的字节。码位值越高,它在 UTF-8 中需要的字节数就越多。
切入正题:
如果将字符串重新定义为两个 Byte 字符串和 unicode 字符串,如下所示:
a_byte = b'Ope\xcc\x81rations'
a_unicode = u'Ope\xcc\x81rations'
和
b_byte = b'Op\xc3\xa9rations'
b_unicode = u'Op\xc3\xa9rations'
你会看到:
print 'a_byte lenght is: ', len(a_byte.decode("utf-8"))
#print 'a_unicode lenght is: ',len(a_unicode.encode("utf-8"))
print 'b_byte lenght is: ',len(b_byte.decode("utf-8"))
#print 'b_unicode lenght is: ', len(b_unicode.encode("utf-8"))
输出:
a_byte lenght is: 11
b_byte lenght is: 10
所以你看他们不一样。
我的解决方案:
如果你不想混淆,那么你可以使用repr(),同时打印a_byte,b_byte打印Opérations作为输出,但是:
print repr(a_byte),repr(b_byte)
将返回:
'Ope\xcc\x81rations','Op\xc3\xa9rations'
还可以将比较前的unicode归一化为@Daniel's answer,如下:
from unicodedata import normalize
from functools import partial
a_byte = 'Opérations'
norm = partial(normalize, 'NFC')
your_string = norm(a_byte.decode('utf8'))