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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With