简体   繁体   English

如何在Python中将unicode代码转换为字符串?

[英]How do I convert unicode code to string in Python?

One of my string variables contains unicode code \ر\َ\ج\ا . 我的一个字符串变量包含unicode代码\ر\َ\ج\ا I want to convert it to a string and see what characters were encoded by it. 我想将它转换为字符串,看看它编码的字符是什么。

Is it possible and how can I do it in python? 有可能,我怎么能在python中做到这一点?

That's just an internal representation. 这只是一个内部代表。 If you print it, you will get what you want: 如果你打印它,你会得到你想要的:

>>> print("\u0631\u064e\u062c\u0627")
رَجا

In short, this is how Python stores the characters رَ and جا . 简而言之,这就是Python存储角色رَجا If you tell Python to print them, you'll see them converted back to their human-readable form. 如果你告诉Python打印它们,你会看到它们转换回人类可读的形式。

Decode using unicode_escape encoding : 使用unicode_escape编码解码:

In Python 2.x: 在Python 2.x中:

>>> text = r'\u0631\u064e\u062c\u0627'
>>> print(text)
\u0631\u064e\u062c\u0627
>>> print(text.decode('unicode-escape'))
رَجا

In Python 3.x: 在Python 3.x中:

>>> text = r'\u0631\u064e\u062c\u0627'
>>> print(text.encode().decode('unicode-escape'))
رَجا
>>> print u"\u0631\u064e\u062c\u0627"
رَجا

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM