簡體   English   中英

bytearray 到字符串 python2 到 3

[英]bytearray to string python2 to 3

我需要在 python3 上將 bytearray 作為字符串獲取。 在 python 2.7 上,str(bytearray) 以字符串格式生成 bytearray 的內容。

    Python 2.7.18 (default, Feb  8 2022, 09:11:29)
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> c = bytearray(b'\x80\x04\x95h\x00\x00')
    >>> str(c)
    '\x80\x04\x95h\x00\x00'
    >>>

在 python 3.6 上,甚至將“bytearray”關鍵字添加到結果字符串中。

    Python 3.6.8 (default, Aug 12 2021, 07:06:15)
    [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> c = bytearray(b'\x80\x04\x95h\x00\x00')
    >>> str(c)
    "bytearray(b'\\x80\\x04\\x95h\\x00\\x00')"
    >>>
  1. 為什么在 3.6 上會這樣?
  2. 如何在 3.6 上獲得與 2.7 完全相同的行為? 注意:我不能執行 c.decode(),因為這些是壓縮/腌制數據,會導致無效的起始字節錯誤。

請有任何建議。

bytearray class 的__str__方法與 Python 不同 3,要獲得類似的結果,您可以嘗試下面的代碼片段。

>>> str(bytes(c))
"b'\\x80\\x04\\x95h\\x00\\x00'"

暫無
暫無

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

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