1

I have this, via the Github API, after base64 decoding:

[b'<!DOCTYPE html>\n', b'<html>\n', b'    <head>\n']

And I'd really like a string (with \n line endings), or a list of strings.

I spent an hour chasing TypeError: a bytes-like object is required, not 'str' because I thought it was already a list of strings, and questioning my own lambda/filter skills before I realized the root cause was somewhere else. I tried googling but I only get hits for 'python bytes to string' which is different.

1
  • How is "python bytes to string" different? Commented Mar 6, 2017 at 12:25

1 Answer 1

4

You could just map the bytes.decode method to each element and then join it if you need a single string:

l = [b'<!DOCTYPE html>\n', b'<html>\n', b'    <head>\n']
s = "".join(map(bytes.decode, l))

or, call decode on each element in a list-comp if you need a list:

ls = [i.decode() for i in l]

With the results now being:

>>> print(repr(s))  # repr to show \n 
'<!DOCTYPE html>\n<html>\n    <head>\n'
>>> print(ls)
['<!DOCTYPE html>\n', '<html>\n', '    <head>\n']
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I can't help but wonder if the error message for TypeError: a bytes-like object is required, not str could be more helpful for noobs
Thanks for your great help. I was working on something cmd & tkinter. So I need these help.

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.