Python 字符串转 unicode [英] Python string to unicode

查看:85
本文介绍了Python 字符串转 unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
怎么做我将 ASCII 字符串视为 unicode 并在 python 中对其中的转义字符进行转义?
如何转换unicode转义序列对python字符串中的字符进行Unicode编码

我有一个包含 unicode 字符的字符串,例如\u2026 等等.不知何故,它不是作为 unicode 接收到我的,而是作为 str 接收的.如何将其转换回 unicode?<预><代码>>>>a="你好\u2026">>>b=u"你好\u2026">>>打印一个你好\u2026>>>打印 b你好…>>>打印 unicode(a)你好\u2026>>>

很明显 unicode(a) 不是答案.那是什么?

解决方案

Unicode 转义只适用于 unicode 字符串,所以这个

 a="\u2026"

实际上是一个6个字符的字符串:'\'、'u'、'2'、'0'、'2'、'6'.

要从中生成 unicode,请使用 decode('unicode-escape'):

a="\u2026"打印代表(a)打印 repr(a.decode('unicode-escape'))## '\\u2026'##你'\u2026'

Possible Duplicate:
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
How do convert unicode escape sequences to unicode characters in a python string

I have a string that contains unicode characters e.g. \u2026 etc. Somehow it is not received to me as unicode, but is received as a str. How do I convert it back to unicode?

>>> a="Hello\u2026"
>>> b=u"Hello\u2026"
>>> print a
Hello\u2026
>>> print b
Hello…
>>> print unicode(a)
Hello\u2026
>>> 

So clearly unicode(a) is not the answer. Then what is?

解决方案

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

这篇关于Python 字符串转 unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆