如何在python中将unicode字符串转换为普通文本 [英] How to convert unicode string into normal text in python

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

问题描述

考虑一下,我有一个Unicode字符串(不是真正的unicode,而是看起来像unicode的字符串).我想得到它的utf-8变体.如何在Python中完成? 例如,如果我有String这样的话:

Consider I have a Unicode string (Not the real unicode but the string that looks like unicode). and I want to get it's utf-8 variant. How can I do it in Python? For example If I have String like:

title = "\\u10d8\\u10e1\\u10e0\\u10d0\\u10d4\\u10da\\u10d8 == \\u10d8\\u10d4\\u10e0\\u10e3\\u10e1\\u10d0\\u10da\\u10d8\\u10db\\u10d8"

如何做到这一点,以便获得其utf-8变体(乔治亚州符号):

How Can I do it so that I get its utf-8 variant (Georgian symbols):

ისრაელი==იერუსალიმი

ისრაელი == იერუსალიმი

简单地说,我想拥有类似以下代码:

To say it simply I want to Have code like:

title = "\\u10d8\\u10e1\\u10e0\\u10d0\\u10d4\\u10da\\u10d8 == \\u10d8\\u10d4\\u10e0\\u10e3\\u10e1\\u10d0\\u10da\\u10d8\\u10db\\u10d8"
utfTitle = title.TurnToUTF()
print(utfTitle)

我希望此代码具有输出:

And I want this code to have output:

ისრაელი==იერუსალიმი

ისრაელი == იერუსალიმი

推荐答案

您可以使用 unicode-escape 编解码器可消除双反斜杠并有效地使用字符串.

You can use the unicode-escape codec to get rid of the doubled-backslashes and use the string effectively.

假设titlestr,则需要先对字符串进行编码,然后再解码回unicode(str).

Assuming that title is a str, you will need to encode the string first before decoding back to unicode(str).

>>> t = title.encode('utf-8').decode('unicode-escape')
>>> t
'ისრაელი == იერუსალიმი'

如果titlebytes实例,则可以直接解码:

If title is a bytes instance you can decode directly:

>>> t = title.decode('unicode-escape')
>>> t
'ისრაელი == იერუსალიმი'

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

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