简体   繁体   English

如何打印这些字符?

[英]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:. 但是在blah之后,这会在第二行打印出看起来很滑稽的人物: How do I get this to work? 我如何让它工作?

The \\xNN notation in a string translates to the character with code NN . 字符串中的\\xNN表示法转换为代码为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 . 为了使你的replace方法能够做你想要的,你需要为它提供一个字符串,它可以找到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: 假设您只想转义扩展的ASCII字符,我会这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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