Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

string - Python unicode character conversion for Emoji

I'm having some issues with formatting a byte ordered mark to unicode. There is some oddness coming in with how my character is being expressed. Basically it's not printing an emoji character in Python, instead it's just the string. Here's my example.

# these codes are coming from a json file; this a representation of one of the codes.
e = 'U+1F600' # smile grin emoji

# not sure how to clean this, so here's a basic attempt using regex.
b = re.compile(r'U+', re.DOTALL).sub('U000', e)

print unicode(b) # output should be 'U0001F600'

For whatever reason this doesn't print an emoji character.

However if you type out the same string as a literal, using the u flag everything works as expected.

print u'U0001F600'

What am I doing wrong here? I thought that the unicode function would convert my string to the working equivalent, but it apparently is not.

I'm using Python 2.7

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess decode is what you are looking for,

>>> b = 'U0001F600'
>>> print b.decode('unicode-escape')
??

or

>>> print unicode(b, 'unicode-escape')
??

The issue with

print unicode(b)

is that the unicode function tries to convert the string U0001F600 to unicode which results in \U0001F600. To prevent this we provide the current encoding as unicode-escape


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...