My Google-fu isn’t good enough for this one.
For Learn Python3 The Hard Way Exercise 23, under Breaking It: 3) I sort of got that bit to work, but I had to cheat and put the actual byte string in the script and break the loop. Like so:
Some Terrible Code
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
print(">>>> Entering main function")
line = language_file #.readline – I’m not reading a line right now
if line: print_line(line, encoding, errors) #return main(language_file, encoding, errors) print("<<<< Exiting main function")
def print_line(line, encoding, errors):
print(">> Entering print_line function")
next_lang = line.strip()
cooked_string = next_lang.decode(encoding, errors=errors)
raw_bytes = cooked_string.encode(encoding, errors=errors)
print(cooked_string, "<====>", raw_bytes) print("<< Exiting print_line function")
languages = b’\xd0\x90\xd2\xa7\xd1\x81\xd1\x88\xd3\x99\xd0\xb0’ #or another byte string
#languages = open(‘bytes.txt’)
#languages = open(“bytes.txt”, ‘r’, ‘b’)
#languages = open(“bytes.txt”, encoding=“utf-8”)
#none of these lets python read the context of “bytes.txt” as a byte string
main(languages, input_encoding, error)
That works fine, but I can’t quite figure out how if I have a text file with a few lines of typed out byte strings to get python to read them as byte strings and not a strings.
I tried changing the parameters of opening the file away from encoding=“utf-8”, I tried just a default open with no parameters and with ‘r’ and ‘b’ as parameters. I also, not displayed here, tried futzing with the actual input-encoding, but I’m not sure if that makes a difference. Regardless, no matter what change I’ve made whenever I print next_lang rather than a byte string it prints out something like
Which does make total sense with the double slashes if that was a string, but I don’t want Python to read the lines as a string.
I’m sure I’m missing some obvious way to Google this, but I’m not sure what I should be precisely Googling, which usually isn’t something I run into. A hint or slight point in the right direction is all I really need here.