Search code examples
pythonunicodeemojipython-unicodepython-3.9

Unicode for an emoji in a string variable isn't shown as the emoji


First of all, sorry for my poor and approximate english...

I'm trying to do a Python script, who should retrieve a variable that will represent the unicode code corresponding to an emoji (U000xxxx). The final goal of this part of the program is to have translated, from unicode, in the name of the emoji.

Since I know that in Python to display an emoji it is print("\U000XXXXX") , so I added the \ before the previous name. But when I print the final rendering is not the one expected

unicode = "U0001f0cf"
unicode = (f"\{unicode}") #OR# unicode = "\%s" %unicode
print (unicode) #>>> \U0001f0cf
#Expected >>> 🃏

I tried a lot of things including .encode() but Python told me I couldn't use a string pattern on an object of type bytes (?)

This is the part that is causing me problem, all the rest of the process is ok... To translate the name of the emoji, from unicode, I found this method (crafted from another Stackoverflow topic)

name = emojis.decode(unicode).replace("_"," ").replace(":","")
print(name) #>>> \U0001f0cf

Whereas if I directly enter the unicode code it works...

name = emojis.decode("U0001f0cf").replace("_"," ").replace(":","")
print(name) #>>> :black_joker:

Thank you very much to anyone who will try to help me, Have a good evening


Solution

  • First get the numeric part from the variable, then use chr() to convert it to its Unicode equivalent, then use the unicodedata database to fetch its name:

    import unicodedata as ud
    
    u = 'U0001f0cf'
    i = int(u[1:],16)
    c = chr(i)
    n = ud.name(c)
    print(c,n)
    

    Output:

    🃏 PLAYING CARD BLACK JOKER
    

    You can also use a range loop to display a number of emoji:

    import unicodedata as ud
    
    for i in range(0x1f0c1,0x1f0d0):
        c = chr(i)
        n = ud.name(c)
        print(c,n)
    

    Output:

    🃁 PLAYING CARD ACE OF DIAMONDS
    🃂 PLAYING CARD TWO OF DIAMONDS
    🃃 PLAYING CARD THREE OF DIAMONDS
    🃄 PLAYING CARD FOUR OF DIAMONDS
    🃅 PLAYING CARD FIVE OF DIAMONDS
    🃆 PLAYING CARD SIX OF DIAMONDS
    🃇 PLAYING CARD SEVEN OF DIAMONDS
    🃈 PLAYING CARD EIGHT OF DIAMONDS
    🃉 PLAYING CARD NINE OF DIAMONDS
    🃊 PLAYING CARD TEN OF DIAMONDS
    🃋 PLAYING CARD JACK OF DIAMONDS
    🃌 PLAYING CARD KNIGHT OF DIAMONDS
    🃍 PLAYING CARD QUEEN OF DIAMONDS
    🃎 PLAYING CARD KING OF DIAMONDS
    🃏 PLAYING CARD BLACK JOKER