无法跳过unicode字符串时出现问题

2024-10-01 17:39:11 发布

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

我有一个问题,无法跳过unicode字符串。我尝试了下面的方法,但它不适用于unicode字符。在

>>> s = ur"\'test\'"
>>> s.decode("string_escape")
"'test'"
>>> s = ur"\'test \u2014\'"
>>> s.decode("string_escape")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 7:
ordinal not in range(128)

有没有更好的方法去除反斜杠?在

顺便说一句:我需要这个,因为xmlrpclib.ServerProxy会跳过响应。

编辑:下面是我的xmlrpc请求示例:

^{pr2}$

我认为越狱来自xmlrpc服务器。在


Tags: 方法字符串intestmoststringunicode字符
2条回答

有趣的是,使用Python 2.6.4时,您发布的错误似乎不会发生:

In [110]: s = ur"\'test\'"

In [111]: s.decode("string_escape")
Out[111]: "'test'"

In [112]: s = ur"\'test \u2014\'"

In [113]: s.decode("string_escape")
Out[113]: "'test \xe2\x80\x94'"

In [114]: print(s.decode("string_escape"))
'test —'

首先,"string_escape"和{},它们都不能解码给定的字符串。第一个读取作为bytestring转义的bytestring,并将其解码为bytestring。第二个读取转义并保存在bytestring中的unicode字符串,因此它无法读取输入的unicode对象,至少不能读取其中包含unicode字符的对象。在

我相信您在这里给出的原始字符串是错误的,您实际上想要s.decode('unicode_escape')作为来自源代码的实际字符串。在

如果我错了,你能做的最好的方法就是用re手动转义任何未转义的单引号,在它周围加上额外的单引号并使用ast.literal_eval。在

def substitute(match):
    if len(match.group(1)) % 2 == 1:
        return match.group()
    else:
        return ur"%s\%s" % (match.group(1), match.group(2))

ast.literal_eval("'%s'" % re.sub(ur"(\\+)(')", substitute, s))

第三种选择是字符串需要传递给ast.literal_eval,而不需要您做任何额外的工作。这三者中的哪一个取决于你到底拥有什么样的字符串。在

JSON可能是我怀疑的另一个对象。你应该给出一个你得到的字符串的例子,以及你从哪里得到的以及如何得到它。在

相关问题 更多 >

    热门问题