【问题标题】:Remove all characters from a string who's ordinals are out of range从字符串中删除序数超出范围的所有字符
【发布时间】:2012-06-11 00:13:40
【问题描述】:

从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)

我认为这意味着一些时髦的字符进入了我试图散列的字符串。

谢谢!

【问题讨论】:

  • 你应该只使用 UTF8 而不是 ASCII
  • 这是处理 unicode 的错误方式的一个例子。

标签: python regex ascii hashlib ordinal


【解决方案1】:
new_safe_str = some_string.encode('ascii','ignore') 

我觉得可以

或者你可以做一个列表理解

"".join([ch for ch in orig_string if ord(ch)<= 128])

[edit] 然而,正如其他人所说,一般情况下弄清楚如何处理 unicode 可能会更好......除非您出于某种原因确实需要将其编码为 ascii

【讨论】:

  • 这是公认的答案,因为它是唯一适用于我的用例的答案。很高兴提前知道哈希函数需要更多的微管理才能正常工作,但是现在数百万个数据库条目使用当前的哈希方法具有辅助键,我无法更改它。
【解决方案2】:

这是一个示例,说明 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")

【讨论】:

    【解决方案3】:

    与其删除这些字符,不如使用 hashlib 不会阻塞的编码,例如 utf-8:

    >>> data = u'\u200e'
    >>> hashlib.sha256(data.encode('utf-8')).hexdigest()
    'e76d0bc0e98b2ad56c38eebda51da277a591043c9bc3f5c5e42cd167abc7393e'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2012-08-14
      • 2014-08-07
      • 1970-01-01
      相关资源
      最近更新 更多