Skip to main content
 首页 » 编程设计

python之如何将非 ascii 字符打印为\uXXXX 文字

2025年05月04日11jillzhang

# what I currently have 
 
print('你好') 
 
# 你好 

# this is what I want 
 
print('你好') 
 
# \uXXXX \uXXXX 

我该怎么做?我想将字符串中的所有非 ascii 字符打印为 unicode 转义文字

请您参考如下方法:

您可以将字符串转换为调试表示,使用 ascii() function 将非 ASCII、不可打印的字符转换为转义序列。 :

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes.

对于 U+0100-U+FFFF 范围内的 Unicode 代码点,这使用 \uhhhh 转义;对于 Latin-1 范围 (U+007F-U+00FF),使用 \xhh 转义。请注意,输出符合重新创建字符串的有效 Python 语法,因此包含引号:

>>> print('你好') 
你好 
>>> print(ascii('你好')) 
'\u4f60\u597d' 
>>> print(ascii('ASCII is not changed, Latin-1 (åéîøü) is, as are all higher codepoints, such as 你好')) 
'ASCII is not changed, Latin-1 (\xe5\xe9\xee\xf8\xfc) is, as are all higher codepoints, such as \u4f60\u597d' 

如果您必须对所有内容都使用\uhhhh,则您必须自己进行转换:

import re 
 
def escape_unicode(t, _p=re.compile(r'[\u0080-\U0010ffff]')): 
    def escape(match): 
        char = ord(match.group()) 
        return '\\u{:04x}'.format(char) if char < 0x10000 else '\\U{:08x}'.format(char) 
    return _p.sub(escape, t) 

上面的函数不像ascii()函数那样添加引号:

>>> print(escape_unicode('你好')) 
\u4f60\u597d 
>>> print(escape_unicode('ASCII is not changed, Latin-1 (åéîøü) is, as are all higher codepoints, such as 你好')) 
ASCII is not changed, Latin-1 (\u00e5\u00e9\u00ee\u00f8\u00fc) is, as are all higher codepoints, such as \u4f60\u597d