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.
>>> 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
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))
请注意,如果不将}(ascii范围内的6个字符),因为这两者都会产生
\
替换为\\
,那么您所需要的是不可逆的;例如,您无法知道实际的字符串是'好'
(一个字符)还是{\u597d
作为输出。Martijn的建议是反斜杠的替代,而且是可逆的。在你可以自己转换:
(Martijn关于BMP之外字符的注释仍然适用)
如果您想对程序输出的所有内容都执行此操作,并且试图记住通过转换函数传递所有内容似乎不是您的理想时间,您也可以尝试以下方法:
^{pr2}$这将创建一个自定义编码错误处理程序,该处理程序通过用unicode转义符替换有问题的字符来处理unicodeencodeerror。您可以像
'你好'.encode('ascii', 'unicodeescapereplace')
一样使用它,或者像上面的例子一样,将stdout替换为一个对所有编码都自动使用它的stdout。在您可以使用^{} function :
对于范围U+0100-U+FFFF中的Unicode码位,使用
\uhhhh
转义符;对于拉丁语1范围(U+007F-U+00FF),使用\xhh
转义符。请注意,输出限定为有效的Python语法以重新创建字符串,因此包含引号:如果您必须拥有
^{pr2}$\uhhhh
来处理所有事情,那么您必须自己进行转换:上面的函数会像
ascii()
函数那样添加引号:正态表示是通过Martijn Pieters使用
ascii
内建函数得到的。在如果您真的想连续打印\u escape,可以用手:
如预期所示:
^{pr2}$注意:我确实知道eval是邪恶的,但在那个特定的用例中,我知道内部字符串不包含
'
,并且它被包含在'
中,因此它不能仅仅是编码字符的转换-但是我决不会在没有至少测试t.contains("'")
的情况下对外部字符串执行此操作。。。在NB2:此方法无法正确处理代码大于0xffff的字符-如果不是,则需要另一个。。。在
相关问题 更多 >
编程相关推荐