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.
I have tried to implement this with an empty string then concatenating it with a for loop but I am unable to get the correct answer.
def div2bstr(bstr):
final_str = ''
final_str += [i//2 for i in bstr]
return final_str
When calling div2bstr(b'Hello'), the expected result is b'$2667'.
I receive errors when I run mine:
final_str += [i//2 for i in bstr]
TypeError: can't concat bytes to list
I understand that when I am i is an integer and that’s why it is unable to concatenate, but I don’t know how to fix this issue and get the proper result.
final_str=''it is a str instead of byte string 2)final_str += [i//2 for i in bstr]left side is astrwhile right side is an int list, which is obviously incorrect 3) I believe you have something else happening in code as theTypeErrorseems not reflecting your mistakes.[i//2 for i in bstr]is what we call list comprehension, it is not a for loop (although you can write a equivalent for-loop based on that)