I cannot figure out how to feed the list of decimal codepoints for them to be decoded (or encoded?) via a specific codepage.
str_0 = 'abc'
lst_decimal = list(str_0.encode("utf-8"))
for i in lst_decimal:
print (str(int(i)).decode("cp437"))
Error: 'str' object has no attribute 'decode'
1 Answer 1
str_0.encode("utf-8") returns a bytes object, which has a decode method, but when you turn it into a list, it becomes a list on ints. Just keep it as a bytes object:
my_bytes = str_0.encode("utf-8")
print (my_bytes.decode("cp437")) #prints abc
Even more simply:
print(str_0.encode("utf-8").decode("cp437"))
As an added benefit, there is no need for using decode in a loop -- the entire bytes object can be decoded at once.
If you wanted to keep your original lst_decimal and do what you were trying to do, your loop could look like:
for i in lst_decimal:
print(bytes([i]).decode("cp437"))
list() turns a bytes object into a list of ints, and bytes goes backwards. Note, however that simply bytes(i) returns a list of i bytes, each initialized to 0.
2 Comments
int(i) is superfluous. bytes([i]).decode() works -- but note the square brackets! There is an int.to_bytes() method, but it isn't very convenient (you need specify number of bytes and byte order). One complicating fact is that when you convert bytes to a list of ints, those ints are in range 0-255. With Unicode, an individual character might correspond to 2 or even more bytes. ord() gives you the actual codepoint of a Unicode character.