Ex23 extra reverse exercise


#1

Trying the suggested extra. My file looks like:

cat languages_bytes.txt
b’\xe1\x8a\xa0\xe1\x88\x9b\xe1\x88\xad\xe1\x8a\x9b’
…/…
b’\xd7\x99\xd7\x99\xd6\xb4\xd7\x93\xd7\x99\xd7\xa9’

and my code looks like:

import sys

script = sys.argv

def main(language_file):
raw_bytes=language_file.readline()
if raw_bytes:
print(raw_bytes.strip())
# the following line fails with
# AttributeError: ‘str’ object has no attribute ‘decode’
# and I don’t know why:
#print(raw_bytes.decode())
return main(language_file)

languages = open(“languages_bytes.txt”)

main(languages)

as mentioned in the comments, print(raw_bytes.decode()) fails with error.

Why?

In Python:

python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.

raw_bytes = b’\xe6\x96\x87\xe8\xa8\x80’
print(raw_bytes)
b’\xe6\x96\x87\xe8\xa8\x80’

print(raw_bytes.decode())
文言


#2

Actually skip that one and move on. I need to take that out of the book.


#3

There is a file type called bytes, you run type(raw_bytes), combined with # AttributeError: ‘str’ object has no attribute ‘decode’, you should be able to understand!


#4

Not really. “encode” and “decode” are terrible words that are ambiguous as to what operation they’re performing. They’re mostly arbitrarily chosen and can mean either operation. That’s why it’s confusing to people so mostly they just deal with it when they need to in the future rather than memorizing which one does what.