Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将unicode格式的字符串转换为unicode格式?_Python_Python 2.7_Unicode - Fatal编程技术网

Python 如何将unicode格式的字符串转换为unicode格式?

Python 如何将unicode格式的字符串转换为unicode格式?,python,python-2.7,unicode,Python,Python 2.7,Unicode,我有一个字符串为“\u96e8”的变量,我想将其转换为unicode,因为kanji_to_romaji函数只接受unicode。我该怎么做?我使用的是python 2.7 # -*- coding: UTF-8 -*- from kanji_to_romaji import kanji_to_romaji message = '\u96e8' message = unicode(message) x = kanji_to_romaji(message) print(x) 使用ast.lite

我有一个字符串为“\u96e8”的变量,我想将其转换为unicode,因为kanji_to_romaji函数只接受unicode。我该怎么做?我使用的是python 2.7

# -*- coding: UTF-8 -*-
from kanji_to_romaji import kanji_to_romaji
message = '\u96e8'
message = unicode(message)
x = kanji_to_romaji(message)
print(x)
使用ast.literal\u eval:

诀窍是构造一个包含unicode字符串文本的字符串,作为参数传递给literal_eval。也就是说,u\u96e8而不仅仅是\u96e8


不过,这只是部分正确。如果消息本身的值包含双引号,则它将失败。在其他情况下,这种方法可能也会失败。

您可以使用unicode转义编解码器将bytestring解码为unicode


建议的复制的可能重复处理从有效编码而不是从Python文本中恢复Unicode字符串。考虑到我回答中的问题,最好的解决方案是首先避免使用这样的字符串。它是从哪里来的?
>>> message = '\u96e8'
>>> ast.literal_eval('u"{}"'.format(message))
u'\u96e8'
>>> message = '\u96e8'
>>> unicode_message = message.decode('unicode-escape')
>>> unicode_message
u'\u96e8'
>>> print unicode_message
雨