Carol Ward
Carol Ward

Reputation: 731

Why am I getting \xc2 when I convert int to character using chr()?

In python 2, when I use chr(143) I get \x8f.

But when I do the same thing in python 3, chr(143).encode()produces \xc2\x8f.

Is there a way for me to just get \x8f in python 3? Why am I getting \xc2 in the front?

Upvotes: 2

Views: 1019

Answers (2)

Ralf
Ralf

Reputation: 16515

You could try using a different encoding, as they produce different results. The default is utf-8.

I tried this (using python 3):

>>> chr(143).encode('latin')
b'\x8f'
>>> chr(143).encode('utf-8')
b'\xc2\x8f'
>>> chr(143).encode('utf-16')
b'\xff\xfe\x8f\x00'

Upvotes: 3

blhsing
blhsing

Reputation: 107005

You can use int.to_bytes:

>>> (143).to_bytes(1, 'big')
b'\x8f'
>>>

Upvotes: 2

Related Questions