簡體   English   中英

使用ROT13的codecs.decode中可能存在錯誤

[英]Possible Bug in codecs.decode using ROT13

Ubuntu上的Python 3.5.1

>>> from codecs import decode
>>> s = 'string'
>>> b = b'bytes'
>>> decode(b, 'utf8')
'bytes'
>>> decode(s, 'utf8')
Traceback (most recent call last):
  File "/usr/lib/python3.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
TypeError: a bytes-like object is required, not 'str'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding with 'utf8' codec failed (TypeError: a bytes-like object is required, not 'str')

到目前為止,一切都按預期進行。 但是,當我嘗試使用ROT13編碼時,我得到:

>>> decode(s, 'rot13')
'fgevat'
>>> decode(b, 'rot13')
Traceback (most recent call last):
  File "/usr/lib/python3.5/encodings/rot_13.py", line 18, in decode
    return (input.translate(rot13_map), len(input))
TypeError: a bytes-like object is required, not 'dict'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding with 'rot13' codec failed (TypeError: a bytes-like object is required, not 'dict')

正如@snakecharmerb指出的那樣,ROT13編碼/解碼僅適用於字符串。
但是,異常Message仍然是錯誤的,因為它指出,即使實際上傳遞了類似字節的對象,也希望使用類似字節的對象,並且提到了用戶未創建的一些詞典。

關於ROT13編解碼器, Python 3.5文檔指出

以下編解碼器提供了文本轉換:str到str的映射。 str.encode()不支持它(僅產生字節輸出)。

也就是說,在編碼到ROT13時,您只能傳遞unicode字符串( str對象),並且只會返回str對象。

當ROT13與其他編解碼器相同時,這與Python 2.x不同。 ROT13最初並未移植到Python 3,因為ROT13不會將unicode字符串編碼為字節-只是交換字母。 恢復后,作為Python 3.2和3.4中的文本轉換。 完整的故事在這個bug報告中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM