9

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.

Lucas Kauffman
  • 6,496
  • 15
  • 59
  • 82
Modelesq
  • 4,850
  • 17
  • 57
  • 82
  • You shoudl adjust the title of your question. The question has nothing to do with utf-8 at all. – Achim May 20 '13 at 20:47

4 Answers4

13

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.

poke
  • 339,995
  • 66
  • 523
  • 574
7
>>> print u'\N{BLACK UP-POINTING TRIANGLE}'
▲
jamylak
  • 120,885
  • 29
  • 225
  • 225
2

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

Community
  • 1
  • 1
David Wolever
  • 139,281
  • 83
  • 327
  • 490
1
>>> icon = '\u25B2'
>>> print(icon)
▲

Also refer to: Python unicode character codes?

Community
  • 1
  • 1
Lucas Kauffman
  • 6,496
  • 15
  • 59
  • 82