簡體   English   中英

如何從字節字符串中刪除一些字節?

[英]How to remove some bytes from a byte string?

我正在嘗試從字節字符串sByte中刪除一個字節( \x00\x81 )。

sByte = b'\x00\x81308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'

我期望結果如下:

sByte = b'308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'

我嘗試了以下方法:

  1. 我試圖解碼sByte 運行下面的代碼行后,

     sByte.decode('utf-8')

    我收到回溯: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 1: invalid start byte

  2. 我也嘗試了以下方法,但沒有奏效:

     sByte.replace('\x00\x81', '')
  3. 我還發現了這個:
    json - UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte ) 但它無助於刪除\x00\x81

不確定我們如何刪除或替換字節字符串中的一個字節。

bytes.replace不能就地工作,它返回bytes object 的修改副本。 您可以使用sByte = sByte.replace(b'\x00\x81', b'') (或bytes.removeprefix如果字節總是出現在開頭)。 根據您的情況,您還可以將decode方法的errors參數設置為'ignore'sByte = sByte.decode(encoding='utf-8', errors='ignore')

>>> sByte = b'\x00\x81308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'
>>> sByte[2:]
b'308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'

另請參閱https://appdividend.com/2022/07/09/python-slice-notation/

代碼片段從第三個字節(包括第三個字節)返回sByte ,直到結束。

如果你想再次存儲變量,你可以這樣做:

>>> sByte = b'\x00\x81308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'
>>> sByte = sByte[2:]
>>> sByte
b'308 921 q53 246 133 137 022 1   0 1 1  1 130 C13 330 0000000199 04002201\n'

暫無
暫無

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

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