Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print these characters?

Tags:

python

I have a string:

"\\xB9 blah\n   blah: \xbf\xaa\xb7\xa2\xb2\xbf\n" 

I want this to be printed as:

\\xB9 blah
   blah: \\xbf\\xaa\\xb7\\xa2\\xb2\\xbf

I have tried:

s = "\\xB9 blah\n   blah: \xbf\xaa\xb7\xa2\xb2\xbf\n"
s = s.replace(r'\x',r'\\x')                                                     
print s

but this prints out funny looking characters on the second line after blah:. How do I get this to work?

like image 490
smithy Avatar asked Mar 26 '26 01:03

smithy


1 Answers

The \xNN notation in a string translates to the character with code NN. In order for your replace method to do what you intend, you need to provide it with a string where it can find the substring \x. You can use raw string, or simply escape the backslashes :

s = r"\\xB9 blah\n   blah: \xbf\xaa\xb7\xa2\xb2\xbf\n"
s = s.replace(r'\x',r'\\x')

.

s = "\\xB9 blah\n   blah: \\xbf\\xaa\\xb7\\xa2\\xb2\\xbf\n"
s = s.replace(r'\x',r'\\x')

If you want to print the escaped versions of the litteral characters, that's a bit more tricky. Assuming you only want the extended ASCII chars to be escaped, I'd do:

def escape_non_ascii(s):
    out = ''
    for c in s:
        if 31 < ord(c) < 127:
            out += c
        elif c == '\n':
            out += r'\n'
        else:
            out += r'\x{0:x}'.format(ord(c))
    return out

print escape_non_ascii("\\xB9 blah\n   blah: \xbf\xaa\xb7\xa2\xb2\xbf\n")
like image 162
svvac Avatar answered Mar 29 '26 13:03

svvac