Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python -> replace escape character to convert hexa string from 0x to \x

i'm trying to print ascii or extended ascii character. using this code :

print '\xff'.decode('latin-1')

it will print ascii #255, but now i want to input using decimal number like this :

num=255
myhex=hex(num) 
print myhex.decode('latin-1')

It doesn't work coz myhex is '0xff' , so i need to convert into '\xff'. replacing the '0x' with '\x' is giving me error.

myhex.replace('0x','\x') 

will give me error : ValueError: invalid \x escape

How to solve the problem? anyone can help ? the goal i want to print char -> ÿ in terminal/console.

like image 646
andio Avatar asked Mar 30 '26 16:03

andio


2 Answers

what you're searching for is

chr(255)

In python2, that gives you a character with binary value 255. If you print that to a terminal that uses UTF8, it will show up as ? (or similar) because the terminal doesn't know what to do with it. To convert that to it's unicode codepoint, you can decode it:

chr(255).decode('latin1')

In python3, chr(255) already gives you the unicode charcter 'LATIN SMALL LETTER Y WITH DIAERESIS'.

you could also do the same in python2 using

unichr(255)
like image 150
mata Avatar answered Apr 02 '26 13:04

mata


>>> print chr(255).decode("latin-1")
ÿ
like image 30
moooeeeep Avatar answered Apr 02 '26 12:04

moooeeeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!