7

I am doing a Python challenge but when in mission 6 I met some problems:

comments = []
comments.append(file_zip.getinfo('%s.txt'%name).comment)
print(''.join(comments))

but this give me the error:

TypeError: sequence item 0: expected str instance, bytes found

I looked for the answer, and have a try like this:

print(b''.join(comments))

it works and prints:

b'***************************************************************\n****************************************************************\n**                                                    **\n**   OO    OO    XX    YYYY    GG    GG  EEEEEE NN      NN  **\n**    OO    OO  XXXXXX   YYYYYY   GG
    GG   EEEEEE  NN    NN   **\n**   OO    OO XXX  XXX YYY   YY  GG GG     EE       NN  NN    **\n**    OOOOOOOO XX    XX YY        GGG       EEEEE     NNNN     **\n**   OOOOOOOO XX    XX YY        GGG       EEEEE      NN      **\n**   OO    OO XXX  XXX YYY   YY  GG GG     EE         NN      **\n**
 OO    OO  XXXXXX   YYYYYY   GG   GG   EEEEEE     NN      **\n**   OO      OO         XX       YYYY    GG    GG  EEEEEE     NN  

I think it regards '/n' as a char and print it, but, I don't want that. How can I make it work?

1 Answer 1

11

The issue is that file_zip.getinfo('%s.txt'%name).comment apparently returns a bytes object(s). When you try and join on an str, namely ''.join(..) you get the error:

''.join([b'hello', b'\n', b'world'])    
TypeError: sequence item 0: expected str instance, bytes found

Joining on b'' is a viable alternative but, as you note, it doesn't escape special characters like '\n'; that's expected behavior for bytes instances.

You can either decode the string after it has been joined on b'':

print(b''.join(comments).decode())

Or, decode every element of comments with map and join on an empty string '' as you originally attempted:

print(''.join(map(bytes.decode, comments)))
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.