Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
Modelesq Avatar asked May 20 '13 20:05

Modelesq


People also ask

How do I add a Unicode to a string in Python?

To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2. x, you also need to prefix the string literal with 'u'.

How do you add a Unicode to a string?

Inserting Unicode characters To insert a Unicode character, type the character code, press ALT, and then press X. For example, to type a dollar symbol ($), type 0024, press ALT, and then press X. For more Unicode character codes, see Unicode character code charts by script.

What is the use of Unicode string in Python?

Python's string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters. Unicode (https://www.unicode.org/) is a specification that aims to list every character used by human languages and give each character its own unique code.

What is character u '\ xe9?

The unicode string for \xe9 is an accented e - é


1 Answers

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.

like image 138
poke Avatar answered Nov 01 '22 17:11

poke