Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print python emoji as unicode string

Tags:

I've been trying to output '😄' as '\U0001f604' instead of the smiley, but it doesn't seem to work.

I tried using repr() but it gives me this '\xf0\x9f\x98\x84'. Currently it outputs the smiley which is not what I wanted. encode('unicode_escape') gives me a UnicodeDecodeError.

The smiley was passed as a string to a class method in python. i.e. "I am happy 😄"

like image 724
You Hock Tan Avatar asked Sep 07 '14 05:09

You Hock Tan


People also ask

How do you print Unicode emojis in Python?

Emojis also have a CLDR short name, which can also be used. From the list of unicodes, replace “+” with “000”. For example – “U+1F600” will become “U0001F600” and prefix the unicode with “\” and print it.

How do you make a Unicode string in Python?

You have two options to create Unicode string in Python. Either use decode() , or create a new Unicode string with UTF-8 encoding by unicode(). The unicode() method is unicode(string[, encoding, errors]) , its arguments should be 8-bit strings.


2 Answers

>>> print u'\U0001f604'.encode('unicode-escape')
\U0001f604
like image 197
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 17:09

Ignacio Vazquez-Abrams


Another solution is to use the name aliases and print them using the string literal \N

print('\N{grinning face with smiling eyes}')

Current list of name aliases can be found at https://www.unicode.org/Public/14.0.0/ucd/NamesList-14.0.0d1.txt

like image 43
nth-attempt Avatar answered Sep 30 '22 17:09

nth-attempt