2

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.

2
  • Though DYZ has given a great answer already, I believe there are something you need to pay attention in your code: 1) final_str='' it is a str instead of byte string 2) final_str += [i//2 for i in bstr] left side is a str while right side is an int list, which is obviously incorrect 3) I believe you have something else happening in code as the TypeError seems not reflecting your mistakes. Commented May 8, 2019 at 6:33
  • 4) There is no for-loop. [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) Commented May 8, 2019 at 6:37

1 Answer 1

3

Convert the list of bytes into a bytes object, and you can write the whole function body in one line.

def div2bstr(bstr):
    return bytes(i//2 for i in bstr)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.