简体   繁体   中英

How do I print these characters?

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")

Try this:

s = r"\\xB9 blah\n   blah: \xbf\xaa\xb7\xa2\xb2\xbf\n"
for part in s.split('\\n'):
    print part

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM