How to use Unicode characters in a python string

Question:

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

icon = '▲'
print icon

which should create icon = ‘▲’

but instead it literally returns it in string form: ▲

How can I make this string recognize unicode?

Thank you for your help in advance.

Asked By: Modelesq

||

Answers:

Use u escaping in a unicode string literal:

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

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

Answered By: David Wolever

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:

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

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

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

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

Answered By: poke
>>> icon = 'u25B2'
>>> print(icon)
▲

Also refer to: Python unicode character codes?

Answered By: Lucas Kauffman

Python 3:

>>> print('N{BLACK UP-POINTING TRIANGLE}')
▲

Python 2:

>>> print u'N{BLACK UP-POINTING TRIANGLE}'
▲
Answered By: jamylak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.