如何在python字符串中使用Unicode字符

时间:2021-04-25 20:18:05

I'd like to be able to use unicode in my python string. For instance I have an icon:

我希望能够在我的python字符串中使用unicode。比如我有一个图标:

icon = '▲'
print icon

which should create icon = '▲'

应该创建icon ='▲'

but instead it literally returns it in string form: ▲

但它确实以字符串形式返回它:▲

How can I make this string recognize unicode?

如何让这个字符串识别unicode?

Thank you for your help in advance.

提前谢谢你的帮助。

4 个解决方案

#1


9  

You can use string escape sequences, as documented in the “string and bytes literals” section of the language reference. For Python 3 this would work simply like this:

您可以使用字符串转义序列,如语言参考的“字符串和字节文字”部分中所述。对于Python 3,这可以像这样工作:

>>> icon = '\u25b2'
>>> print(icon)
▲

In Python 2 this only works within unicode strings. Unicode strings have a u prefix before the quotation mark:

在Python 2中,这仅适用于unicode字符串。 Unicode字符串在引号前面有一个u前缀:

>>> icon = u'\u25b2'
>>> print icon
▲

This is not necessary in Python 3 as all strings in Python 3 are unicode strings.

这在Python 3中不是必需的,因为Python 3中的所有字符串都是unicode字符串。

#2


3  

>>> print u'\N{BLACK UP-POINTING TRIANGLE}'
▲

#3


2  

Use \u escaping in a unicode string literal:

在unicode字符串文字中使用\ u转义:

>>> print u"\u25B2".encode("utf-8")
▲

Alternatively, if you want to use HTML entities, you can use this answer: https://*.com/a/2087433/71522

或者,如果要使用HTML实体,可以使用以下答案:https://*.com/a/2087433/71522

#4


1  

>>> icon = '\u25B2'
>>> print(icon)
▲

Also refer to: Python unicode character codes?

另请参阅:Python unicode字符代码?

#1


9  

You can use string escape sequences, as documented in the “string and bytes literals” section of the language reference. For Python 3 this would work simply like this:

您可以使用字符串转义序列,如语言参考的“字符串和字节文字”部分中所述。对于Python 3,这可以像这样工作:

>>> icon = '\u25b2'
>>> print(icon)
▲

In Python 2 this only works within unicode strings. Unicode strings have a u prefix before the quotation mark:

在Python 2中,这仅适用于unicode字符串。 Unicode字符串在引号前面有一个u前缀:

>>> icon = u'\u25b2'
>>> print icon
▲

This is not necessary in Python 3 as all strings in Python 3 are unicode strings.

这在Python 3中不是必需的,因为Python 3中的所有字符串都是unicode字符串。

#2


3  

>>> print u'\N{BLACK UP-POINTING TRIANGLE}'
▲

#3


2  

Use \u escaping in a unicode string literal:

在unicode字符串文字中使用\ u转义:

>>> print u"\u25B2".encode("utf-8")
▲

Alternatively, if you want to use HTML entities, you can use this answer: https://*.com/a/2087433/71522

或者,如果要使用HTML实体,可以使用以下答案:https://*.com/a/2087433/71522

#4


1  

>>> icon = '\u25B2'
>>> print(icon)
▲

Also refer to: Python unicode character codes?

另请参阅:Python unicode字符代码?