Print file of unknown encoding without discovering the encoding

Viewed 32

I have a binary file where 99% of the characters are standard ascii and the 1% could be absolutely anything (including zero) so I don't think it conforms to any standard encoding. I would like to print the contents of this file to screen and I don't mind how the odd characters appear. Is there any such thing as a function like:

string = any_old_junk_binary_to_string(binary)

which will perhaps replace characters it doesn't like with some generic marker character or even or even omit that character?

1 Answers

Yes there is. You can use the errors argument to decode, like this:

string = binary.decode('ASCII', errors="replace")

This will replace any invalid bytes with �. There are other options available depending what you want to do with invalid characters, see this page for a full list.

Related