我正在尝试检查一些字符串是否在一个数组中,就像这样:
intact_columns = [...]
for key, value in obj.iteritems():
if not key in intact_columns:
print key
问题是:数组中存在这样的项目:
Reten\xc3\xa7\xc3\xa3o (RET)
而我要迭代的字符串是这样的:Retenção (RET)
utf-8
(或utf-16)是安全的,然后再进行检查。例如:>>> my_list = ['Reten\xc3\xa7\xc3\xa3o (RET)', 'blah blah ...']
>>> my_string = 'Retenção (RET)'
>>> my_list[0].decode('utf-8')
u'Reten\xe7\xe3o (RET)'
>>> my_string.decode('utf-8')
u'Reten\xe7\xe3o (RET)'
两者具有相同的解码值
首先,您需要真正理解编码...猜测数组中的项目是utf8...您正在检查的项目似乎是unicode
if key.encode("utf8") in intact_columns:
bytestring.decode('utf8') # -> results in unicode
unicodestr.encode('utf8') # -> results in bytestring
'Retenção (RET)'.encode('utf-8')
会出现 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
错误。 - Moinuddin Quadri
if not key.encode('utf8') in intact_columns
? - Nf4r