Search code examples
pythonstringunicode

How to use Unicode characters in a python string


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.


Solution

  • 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.