Python Forum

Full Version: Manually create a hex value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Help collect a string for correct conversion:

It works correctly:
a = '\xcf'
t = a.encode("latin-1").decode("cp1251")
print (t)
:~/Python/5$ ./test1.py
П

And so not right.
b = r'\x' + 'cf'
t = b.encode("latin-1").decode("cp1251")
print (t)
:~/Python/5$ ./test1.py
\xcf

How is it right to do that?
the \x is an escape character which says take the following as hexadecimal number
once separated from each other, the \x by itself fails because there is no value immediately following
a = '' + '\xcf'
would work.
(Feb-21-2020, 12:18 PM)Larz60+ Wrote: [ -> ]the \x is an escape character which says take the following as hexadecimal number
once separated from each other, the \x by itself fails because there is no value immediately following
a = '' + '\xcf'
would work.

Of course, your option works. And how does it differ from my version in the first post ... a = '\xcf' ...?
I want to collect! variable b from two different lines:
'\x' and 'cf' but Python doesn't understand this!
Here is the right solution, in my case:

#!/usr/bin/python3
#coding: utf-8
import binascii

a = 'cf'
print (binascii.unhexlify(a))
print (binascii.unhexlify(a).decode("cp1251"))
:~/Python/5$ ./test1.py
b'\xcf'
П
Try:
print (binascii.unhexlify(a).decode())
Then it's encoded by default as utf-8.
You'll get a different result.
(Feb-25-2020, 08:15 AM)DeaD_EyE Wrote: [ -> ]Try:
print (binascii.unhexlify(a).decode())
Then it's encoded by default as utf-8.
You'll get a different result.

Yes. In my case, this is enough