如何将 unicode 转义序列转换为 python 字符串中的 unicode 字符 [英] How do convert unicode escape sequences to unicode characters in a python string

查看:89
本文介绍了如何将 unicode 转义序列转换为 python 字符串中的 unicode 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用unicode(head.contents[3])"获取标签的内容时,我得到类似于以下内容的输出:Christensen Sk\xf6ld".我希望转义序列作为字符串返回.如何在python中做到这一点?

解决方案

假设 Python 将名称视为普通字符串,您首先必须将其解码为 un​​icode:

<预><代码>>>>名称'克里斯滕森 SK\xf6ld'>>>unicode(名称,'latin-1')u'Christensen Sk\xf6ld'

实现此目的的另一种方法:

<预><代码>>>>name.decode('latin-1')u'Christensen Sk\xf6ld'

注意字符串前面的u",表示它是未编码的.如果你打印这个,带重音的字母会正确显示:

<预><代码>>>>打印 name.decode('latin-1')克里斯滕森·斯科尔德

顺便说一句:必要时,您可以使用 de "encode" 方法将 unicode 转换为例如一个 UTF-8 字符串:

<预><代码>>>>name.decode('latin-1').encode('utf-8')'克里斯滕森 Sk\xc3\xb6ld'

When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?

解决方案

Assuming Python sees the name as a normal string, you'll first have to decode it to unicode:

>>> name
'Christensen Sk\xf6ld'
>>> unicode(name, 'latin-1')
u'Christensen Sk\xf6ld'

Another way of achieving this:

>>> name.decode('latin-1')
u'Christensen Sk\xf6ld'

Note the "u" in front of the string, signalling it is uncode. If you print this, the accented letter is shown properly:

>>> print name.decode('latin-1')
Christensen Sköld

BTW: when necessary, you can use de "encode" method to turn the unicode into e.g. a UTF-8 string:

>>> name.decode('latin-1').encode('utf-8')
'Christensen Sk\xc3\xb6ld'

这篇关于如何将 unicode 转义序列转换为 python 字符串中的 unicode 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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