如何将非科学字符打印为\uxxx

2024-10-08 23:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

# what I currently have

print('你好')

# 你好

^{pr2}$

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


Tags: 字符串haveasciiunicode字符whatprintcurrently
3条回答

请注意,如果不将\替换为\\,那么您所需要的是不可逆的;例如,您无法知道实际的字符串是'好'(一个字符)还是{}(ascii范围内的6个字符),因为这两者都会产生\u597d作为输出。Martijn的建议是反斜杠的替代,而且是可逆的。在

你可以自己转换:

def unicodeescape(s):
    return ''.join(c if ord(c) < 128 else '\\u%04x' % ord(c) for c in s)

print(unicodeescape('你好'))

(Martijn关于BMP之外字符的注释仍然适用)

如果您想对程序输出的所有内容都执行此操作,并且试图记住通过转换函数传递所有内容似乎不是您的理想时间,您也可以尝试以下方法:

^{pr2}$

这将创建一个自定义编码错误处理程序,该处理程序通过用unicode转义符替换有问题的字符来处理unicodeencodeerror。您可以像'你好'.encode('ascii', 'unicodeescapereplace')一样使用它,或者像上面的例子一样,将stdout替换为一个对所有编码都自动使用它的stdout。在

您可以使用^{} function:

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转义符;对于拉丁语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来处理所有事情,那么您必须自己进行转换:

^{pr2}$

上面的函数会像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

正态表示是通过Martijn Pieters使用ascii内建函数得到的。在

如果您真的想连续打印\u escape,可以用手

t = 'ASCII is not changed, Latin-1 (åéîøü) is, as are all higher codepoints, such as 你好'
disp = u = "'" + ''.join([c if (ord(c) < 128) else r'\u%04x' % (ord(c),) for c in t ]) + "'"
print(disp)
print(eval(disp))

如预期所示:

^{pr2}$

注意:我确实知道eval是邪恶的,但在那个特定的用例中,我知道内部字符串不包含',并且它被包含在'中,因此它不能仅仅是编码字符的转换-但是我决不会在没有至少测试t.contains("'")的情况下对外部字符串执行此操作。。。在

NB2:此方法无法正确处理代码大于0xffff的字符-如果不是,则需要另一个。。。在

相关问题 更多 >

    热门问题