Unicode emoji as string to emoji in Python3

Question:

I’m reading a file with a lot of Unicode code (emojis) such as U+1F49B. What I want to do is do something like "U0001F49B", but without writing, I just have the code like this in a variable "U0001FA77"

class Emoji:
    def __init__(self, tipo, codigo):
        self.tipo = tipo
        self.codigo = self.convertirCodigo(codigo)

    def convertirCodigo(self, codigo):
        nuevoCodigo = codigo.replace("+", "000")
        nuevoCodigo.replace("n", "")
        return nuevoCodigo

    def __str__(self):
        return self.codigo

I have a class that contains all the "emojis", I want to know if there’s a way to show the emoji itself with a variable. Instead of that I just get "U0001FA77" as output.

Asked By: Cristian Vega

||

Answers:

You could go from 'U+1F49B' to chr(int('1F49B', 16)), for example:

codigo = 'U+1F49B'
hex_ = codigo.removeprefix("U+")
codepoint = int(hex_, 16)
character = chr(codepoint)
print(character)

Output:

Note: str.removeprefix() was added in Python 3.9. You could just as well do .replace("U+", "") or something else, but I prefer this because it’s more strict about the input.

Answered By: wjandrea
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.