There’s a package for pretty much everything you can think of in the Python ecosystem, all installable with a simple pip command. So it shouldn’t surprise anyone that there’s a package to work with emoji in Python, too. But before you install anything: for many tasks, you don’t need a package at all.
Emoji in plain Python
Python 3 strings are Unicode, and emoji are just Unicode characters. So you can type or paste an emoji straight into a string. If you’d rather keep your source code plain ASCII, use the character’s official Unicode name with \N{...}, or its code point with \U:
print('Python is 👍')
print('Python is \N{THUMBS UP SIGN}')
print('Python is \U0001F44D')
# All three print: Python is 👍
You can look up the name of an emoji with unicodedata.name('👍'), which returns 'THUMBS UP SIGN'.
One thing that often surprises people: len() counts code points, not what you see on screen. Many emoji are made of several code points. A thumbs up with a skin tone is the thumbs up plus a skin tone modifier, and a family emoji is several people glued together with invisible “zero width joiner” characters:
>>> len('👍')
1
>>> len('👍🏽')
2
>>> len('👨👩👧')
5
Keep this in mind when you cut strings to a maximum length, because you might cut an emoji in half.
The Python emoji package
The emoji package is useful when you want to convert between emoji and their text names, like :thumbs_up:, or find and remove emoji in text. You can install the emoji package with:
$ pip install emoji
After installation, you can import the module with import emoji. This package allows you to convert Unicode emoji to a string version, and vice versa:
import emoji
result = emoji.emojize('Python is :thumbs_up:')
print(result)
# 'Python is 👍'
# You can also reverse this:
result = emoji.demojize('Python is 👍')
print(result)
# 'Python is :thumbs_up:'
The package can also count emoji in a text with emoji.emoji_count(), and strip them out with emoji.replace_emoji(text, replace='').
There are several useful use-cases for working with the Python emoji package. For example, it may come in handy when doing data science on social media. It will also help when you don’t want to store emojis in a database: you can use the package to convert them to a text representation first.