当我尝试使用unicode(head.contents[3])"获取标签的内容时,我得到类似于以下内容的输出:Christensen Sk\xf6ld".我希望转义序列作为字符串返回.如何在python中做到这一点?
解决方案假设 Python 将名称视为普通字符串,您首先必须将其解码为 unicode:
>>>名称'克里斯滕森 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öldBTW: 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 字符
发布评论