maxshun maxshun - 2 months ago 13
Python Question

TypeError: sequence item 0 expected str instance, bytes found

I am doing 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.

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?

Answer

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)))