我有一个字符串,它的值是‘Opé口粮’。在我的脚本中,我将读取一个文件并进行一些比较。在比较字符串时,我从同一个源复制并放在python脚本中的字符串不等于我在脚本中读取相同文件时接收到的字符串。打印这两条线给我“行动”。但是,当我将其编码为utf-8时,我注意到了不同之处。
我的问题是,在比较这些字符串时,如何确保python脚本中的特殊字符与文件内容相同。
发布于 2018-12-19 13:38:57
很高兴知道:
您正在讨论两种类型的字符串,字节字符串和unicode字符串。每个都有一个方法将其转换为另一种类型的字符串。unicode字符串有一个产生字节的.encode()方法,而字节字符串有一个生成Unicode的.decode()方法。它的意思是:
unicode.enocde() ->字节
和
bytes.decode() -> unicode
而UTF-8很容易成为存储和传输Unicode最流行的编码方式.它对每个代码点使用可变字节数。代码点值越高,UTF-8中所需的字节就越多.
切入要点:
如果将字符串重新定义为两个Byte字符串和unicode字符串,作为follwos:
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所以你看他们不一样了。
我的解决方案:
如果您不想混淆,那么可以使用瑞尔(),在打印a_byte时,b_byte打印Opérations作为输出,但是:
print repr(a_byte),repr(b_byte)将返回:
'Ope\xcc\x81rations','Op\xc3\xa9rations'您还可以在比较之前将unicode规范化为@Daniel的回答,如下所示:
from unicodedata import normalize
from functools import partial
a_byte = 'Opérations'
norm = partial(normalize, 'NFC')
your_string = norm(a_byte.decode('utf8'))https://stackoverflow.com/questions/53850077
复制相似问题