在python中,去除字符串中所有超出范围ordinal(128)
的字符,有一个好方法是什么?
我正在使用python 2.7中的hashlib.sha256,但是我遇到了以下异常:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u200e' in position 13: ordinal not in range(128)
我猜测这意味着有一些奇怪的字符被引入到我要哈希的字符串中。
谢谢!
在python中,去除字符串中所有超出范围ordinal(128)
的字符,有一个好方法是什么?
我正在使用python 2.7中的hashlib.sha256,但是我遇到了以下异常:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u200e' in position 13: ordinal not in range(128)
我猜测这意味着有一些奇怪的字符被引入到我要哈希的字符串中。
谢谢!
new_safe_str = some_string.encode('ascii','ignore')
我觉得这个方案可行
或者你可以使用列表推导式
"".join([ch for ch in orig_string if ord(ch)<= 128])
[编辑] 然而,正如其他人所说,最好弄清楚如何总体处理 Unicode……除非您真的有某些原因需要将其编码为 ASCII。
不要删除这些字符,最好使用哈希库无法识别但utf-8可以处理的编码方式:
>>> data = u'\u200e'
>>> hashlib.sha256(data.encode('utf-8')).hexdigest()
'e76d0bc0e98b2ad56c38eebda51da277a591043c9bc3f5c5e42cd167abc7393e'
这是一个示例,说明Python3中的变化将会带来改进,或者至少生成更清晰的错误消息。
Python2
>>> import hashlib
>>> funky_string=u"You owe me £100"
>>> hashlib.sha256(funky_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 11: ordinal not in range(128)
>>> hashlib.sha256(funky_string.encode("utf-8")).hexdigest()
'81ebd729153b49aea50f4f510972441b350a802fea19d67da4792b025ab6e68e'
>>>
Python3
>>> import hashlib
>>> funky_string="You owe me £100"
>>> hashlib.sha256(funky_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing
>>> hashlib.sha256(funky_string.encode("utf-8")).hexdigest()
'81ebd729153b49aea50f4f510972441b350a802fea19d67da4792b025ab6e68e'
>>>
实际问题在于sha256
需要一系列字节,而python2没有明确的概念。我建议使用.encode("utf-8")
。