Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 哈希方法和UnicodeError_Python_String_Unicode_Hash - Fatal编程技术网

Python 哈希方法和UnicodeError

Python 哈希方法和UnicodeError,python,string,unicode,hash,Python,String,Unicode,Hash,在Python 2.5中,我有以下哈希函数: def __hash__(self): return hash(str(self)) 它可以很好地满足我的需要,但现在我开始收到以下错误消息。知道发生了什么吗 return hash(str(self)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 16: ordinal not in range(128) 我怎样才能解决这个问题

在Python 2.5中,我有以下哈希函数:

def __hash__(self):
  return hash(str(self))
它可以很好地满足我的需要,但现在我开始收到以下错误消息。知道发生了什么吗

return hash(str(self))
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 16: ordinal not in range(128)
我怎样才能解决这个问题


谢谢

问题是您试图散列一个不能转换为ASCII的字符串。str方法接受unicode对象,并在默认情况下将其转换为ASCII

要解决此问题,您需要直接散列unicode对象,或者使用正确的编解码器转换字符串

例如,如果在美国Windows本地化系统上从控制台读取unicode,则可以执行此操作:

return hash(mystring.encode("cp437"))
另一方面,来自注册表或API函数的数据可能被编码为:

return hash(mystring.encode("cp1252"))
请注意,本地系统的编码根据本地化的不同而不同,因此您需要了解使用区域设置库的内容

我注意到您正在转换str(self),这意味着您需要重写
\uuuuu str\uuuu
方法来在那里进行编码,并且可能在
\uuuu repr\uuuu
中对受影响的对象进行编码


是一个很好的链接,其中包含许多关于Python和unicode的有用信息。请特别参阅“为什么打印不起作用?”

部分。问题是您试图散列一个无法转换为ASCII的字符串。str方法接受unicode对象,并在默认情况下将其转换为ASCII

要解决此问题,您需要直接散列unicode对象,或者使用正确的编解码器转换字符串

例如,如果在美国Windows本地化系统上从控制台读取unicode,则可以执行此操作:

return hash(mystring.encode("cp437"))
另一方面,来自注册表或API函数的数据可能被编码为:

return hash(mystring.encode("cp1252"))
请注意,本地系统的编码根据本地化的不同而不同,因此您需要了解使用区域设置库的内容

我注意到您正在转换str(self),这意味着您需要重写
\uuuuu str\uuuu
方法来在那里进行编码,并且可能在
\uuuu repr\uuuu
中对受影响的对象进行编码


是一个很好的链接,其中包含许多关于Python和unicode的有用信息。请特别参阅“为什么打印不起作用?”

错误似乎不在
\uuuuuu散列函数中,而是在
\uuu str\uuuu
函数中

在有问题的对象中尝试
str(yourobject)
,你就会明白我的意思


请编辑问题并添加您的
\uuuuu str\uuuuu
函数(以及相关数据),以便我们指导您如何更正它。

错误似乎不在
\uuuuu散列函数中,而是在
\uuuu str\uuu
函数中

在有问题的对象中尝试
str(yourobject)
,你就会明白我的意思

请编辑问题并添加您的
\uuu str\uuu
函数(和相关数据),以便我们为您指出如何更正