You Hock Tan
You Hock Tan

Reputation: 1015

print python emoji as unicode string

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 😄"

Upvotes: 28

Views: 95053

Answers (8)

Federico Baù
Federico Baù

Reputation: 7665

Print Unicode with U+ prefix

I was looking a this usefull list of emoji Here and also This one

A part of just copy any emoji like --> 📀 I wanted to map in my code some of this emojy but using the code provided. In the example of the link it would be like -> U+1F4C0 Now if you find the code formatted in this way, what you need to do is the following:

  1. Replace "+" with "000"
  2. Prefix the Unicode with "\"

The result should be :

dict = '\U0001F4C0'
print(disc)
# 📀

Upvotes: 4

nth-attempt
nth-attempt

Reputation: 654

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://unicode.org/Public/15.0.0/ucd/UnicodeData-15.0.0d6.txt

Or the Folder for everything here: https://unicode.org/Public/

Upvotes: 26

Anshika Grover
Anshika Grover

Reputation: 31

I tried this and it worked perfectly fine

print(u'\U0001f604')

So you will get the output

😄

So just put u at beginning of your string. Hope it helps 😄

Upvotes: 2

Emma
Emma

Reputation: 27723

This code might help you to see how you can simply print an emoji:

Code

# -*- coding: UTF-8 -*-
import re

# string = 'Anything else that you wish to match, except URLs http://url.org'
string = 'Anything else that you wish to match'
matches = re.search(r'^(((?!http|https).)+)$', string)
if matches:
    print(matches.group(1)+ " is a match 😄 ")
else: 
    print('🙀 Sorry! No matches! Something is not right!')

Output for string with URL

🙀 Sorry! No matches! Something is not right!

Output for string without URL

Anything else that you wish to match is a match 😄 

Upvotes: 5

Re4per
Re4per

Reputation: 131

Just add

# -*- coding: UTF-8 -*-

into your code and you will be able to print Unicode characters

Upvotes: 13

You Hock Tan
You Hock Tan

Reputation: 1015

I found the solution to the problem.

I wrote the following code:

#convert to unicode
teststring = unicode(teststring, 'utf-8')

#encode it with string escape
teststring = teststring.encode('unicode_escape')

Upvotes: 15

Saish
Saish

Reputation: 521

If this is for debugging purposes, you could use %r as the format specifier.

>>> print '%r' % u'\U0001f604'
u'\U0001f604'

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798636

>>> print u'\U0001f604'.encode('unicode-escape')
\U0001f604

Upvotes: 19

Related Questions