0

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I stumbled upon print (struct.pack('B', int(i).decode('cp866'))), this did what I wanted. But is there a way to it with the method you suggested? 'i' the original decimal value I want to have a possibility to change.
@DmitryStarostin What I gave at the end should work. In your comment here, i is already an integer so 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.