gpt4 book ai didi

python - 划分字节串并作为字节串返回

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:55 25 4
gpt4 key购买 nike

Write a function called div2bstr that takes a byte string (bstr) and returns a byte string. Each character in the byte string is divided by 2 (integer division) and assembled into a new byte string. Return the new byte string using a string and for loop.

我尝试用一​​个空字符串来实现它,然后将它与一个 for 循环连接起来,但我无法得到正确的答案。

def div2bstr(bstr):
final_str = ''
final_str += [i//2 for i in bstr]
return final_str

调用div2bstr(b'Hello')时,预期结果为b'$2667'

我在运行我的程序时收到错误:

final_str += [i//2 for i in bstr]

TypeError: can't concat bytes to list

我知道当我 i 是一个整数时,这就是它无法连接的原因,但我不知道如何解决这个问题并获得正确的结果。

最佳答案

将字节列表转换成一个bytes对象,你可以在一行中写出整个函数体。

def div2bstr(bstr):
return bytes(i//2 for i in bstr)

关于python - 划分字节串并作为字节串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56033684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com