如何确定字符串是否转义为unicode

Ben*_*ack 5 python unicode python-2.x

如何确定字符串是否包含转义的unicode,以便您知道是否要运行.decode("unicode-escape")

例如:

test.py

# -*- coding: utf-8 -*-
str_escaped = '"A\u0026B"'
str_unicode = '"?????? ? ????"'

arr_all_strings = [str_escaped, str_unicode]

def is_escaped_unicode(str):
    #how do I determine if this is escaped unicode?
    pass

for str in arr_all_strings:
    if is_escaped_unicode(str):
        str = str.decode("unicode-escape")
    print str
Run Code Online (Sandbox Code Playgroud)

当前输出:

"A\u0026B"
"?????? ? ????"
Run Code Online (Sandbox Code Playgroud)

预期产量:

"A&B"
"?????? ? ????"
Run Code Online (Sandbox Code Playgroud)

我如何定义is_escaped_unicode(str)以确定传递的字符串是否实际上是转义unicode?

wim*_*wim 7

你不能.

无法判断"A\u0026B"最初是来自某些已编码的文本,还是数据只是字节"A\u0026B",或者我们是否从其他编码到达那里.

怎么做...你知道是否要跑 .decode("unicode-escape")

你必须知道先前是否有人打过电话text.encode('unicode-escape').字节本身无法告诉你.

你可以猜测,通过寻找\ u或\ U转义序列,或者只是尝试/除了解码,看看会发生什么,但我不建议沿着这条路走下去.

如果您在应用程序中遇到字节字符串,并且您还不知道编码是什么,那么您的问题就在其他地方,应该在其他地方修复.


Hah*_*pro 5

str_escaped = u\'"A\\u0026B"\'\nstr_unicode = \'"\xd0\x92\xd0\xbe\xd0\xb9\xd0\xbd\xd0\xb0\xcc\x81 \xd0\xb8 \xd0\xbc\xd0\xb8\xd1\x80\xd1\x8a"\'\n\narr_all_strings = [str_escaped, str_unicode]\n\ndef is_ascii(s):\n    return all(ord(c) < 128 for c in s)\n\ndef is_escaped_unicode(str):\n    #how do I determine if this is escaped unicode?\n    if is_ascii(str): # escaped unicode is ascii\n        return True\n    return False\n\nfor str in arr_all_strings:\n    if is_escaped_unicode(str):\n        str = str.decode("unicode-escape")\n    print str\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下代码适用于您的情况。

\n\n

解释:

\n\n
    \n
  • str_escaped 中的所有字符串都在 Ascii 范围内。

  • \n
  • str_unicode 中的字符不包含在 Ascii 范围内。

  • \n
\n