print python emoji as unicode string

Deadly 提交于 2019-11-26 16:54:07

问题


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 as 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

"

Appreciate if anyone could help.

Sorry for the big smiley. The markdown doesn't seem to work here.


回答1:


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



回答2:


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')



回答3:


Another solution is to use the short names here and print them using the string literal \N

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



回答4:


Just add

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

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




回答5:


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

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



回答6:


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 😄 


来源:https://stackoverflow.com/questions/25707222/print-python-emoji-as-unicode-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!