📖 How-To Guides

How to Use Emojis in Python: A Developer's Complete Guide

Emojis in Python

Python 3's native str type is Unicode, which means emojis are first-class string citizens. You can print them, store them, search for them, and process them with no special setup — as long as you understand a few key concepts about how Unicode and emoji encoding work.

This guide covers every aspect of working with emojis in Python, from simple printing to complex sequence handling and the emoji library.

Basic Emoji Output

The simplest way to include an emoji in Python is to paste the character directly into a string literal:

print("Hello 🌍")
print("Build complete ✅")
message = f"Deployment successful 🚀 — {version}"

Python 3 strings are Unicode by default. Every emoji character is a valid Unicode code point and can appear in any string literal, variable, or f-string as long as your source file is saved as UTF-8UTF-8
การเข้ารหัส Unicode แบบความกว้างผันแปร ใช้ 1 ถึง 4 ไบต์ต่ออักขระ เป็นมาตรฐานหลักบนเว็บ (ใช้โดยเว็บไซต์กว่า 98%)
(the default for Python 3).

Unicode Escape Sequences

You can also reference emojis by their Unicode code point:

# U+1F525 FIRE
fire = "\U0001F525"
print(fire)  # 🔥

# U+1F600 GRINNING FACE
grin = "\U0001F600"
print(grin)  # 😀

# U+2764 HEAVY BLACK HEART (followed by U+FE0F variation selectorVariation Selector (VS)
อักขระ Unicode (VS-15 U+FE0E และ VS-16 U+FE0F) ที่กำหนดว่าอักขระจะแสดงผลเป็นข้อความ (สีเดียว) หรืออิโมจิ (มีสี)
) heart = "\u2764\uFE0F" print(heart) # ❤️

The format is \UXXXXXXXX for code points above U+FFFF (8 hex digits) and \uXXXX for code points at or below U+FFFF (4 hex digits).

The emoji Library

For emoji-heavy applications, the third-party emoji library provides a convenient set of utilities:

pip install emoji

Shortcode to Emoji

import emoji

# Convert shortcodes to emoji characters
text = emoji.emojize("I love :fire: and :heart:")
print(text)  # I love 🔥 and ❤️

# Language options: 'alias' (Slack/GitHub style), 'en', 'es', etc.
text = emoji.emojize(":thumbs_up:", language="alias")
print(text)  # 👍

Emoji to Shortcode (Demojize)

import emoji

text = emoji.demojize("Hello 🌍 from Python 🐍")
print(text)  # Hello :globe_showing_Europe-Africa: from Python :snake:

# Custom delimiters
text = emoji.demojize("🔥", delimiters=("[", "]"))
print(text)  # [fire]

Getting Emoji Metadata

import emoji

info = emoji.emoji_list("I 🔥 love Python 🐍")
# Returns a list of dicts with emoji characters and positions

for item in info:
    print(item)
# {'match_start': 2, 'match_end': 3, 'emoji': '🔥'}
# {'match_start': 14, 'match_end': 15, 'emoji': '🐍'}

Counting Emojis

import emoji

text = "Great job! 🎉🎊✨"
count = emoji.emoji_count(text)
print(count)  # 3

Checking if a String Contains Emojis

import emoji

def has_emoji(text: str) -> bool:
    return emoji.emoji_count(text) > 0

print(has_emoji("Hello 😀"))  # True
print(has_emoji("Hello World"))  # False

String Length and Emoji Grapheme Clusters

One of the most common Python emoji pitfalls: len() counts code points, not visible characters. Many emojis consist of multiple code points joined by invisible characters.

# Simple emoji: 1 code point
fire = "🔥"
print(len(fire))    # 1 ✓

# Skin tone modifier: 2 code points (base + modifier)
thumbs_up = "👍🏽"
print(len(thumbs_up))  # 2 — but renders as 1 visible emoji

# ZWJZero Width Joiner (ZWJ)
อักขระ Unicode ที่มองไม่เห็น (U+200D) ใช้เพื่อเชื่อมอิโมจิหลายตัวเข้าเป็นอิโมจิรวม เช่น การรวมคนและวัตถุเป็นอิโมจิอาชีพ
sequence: 3 code points (woman + ZWJ + laptop) woman_tech = "👩‍💻" print(len(woman_tech)) # 3 — but renders as 1 visible emoji # Family emoji: 7 code points family = "👨‍👩‍👧‍👦" print(len(family)) # 7 — but renders as 1 visible emoji

To count by grapheme clusters (visible characters), use the grapheme library:

pip install grapheme
import grapheme

text = "Hi 👩‍💻!"
print(len(text))              # 8 (code points)
print(grapheme.length(text))  # 5 (visible characters: H, i, space, 👩‍💻, !)

Unicode Normalization

Some emoji can be represented in multiple equivalent Unicode forms. Normalization ensures consistent behavior when comparing or storing emoji text:

import unicodedata

# NFC normalization (recommended for storage and comparison)
text = "Hello 🔥"
normalized = unicodedata.normalize("NFC", text)

For database storage, always normalize to NFC before inserting emoji text. Python's unicodedata.normalize("NFC", s) handles this.

Regex with Emojis

Python's re module works with emoji characters, but you need to use the re.UNICODE flag (the default in Python 3) and be careful with multi-codepoint sequences.

Matching Any Emoji

import re

# Match basic emoji in the Miscellaneous Symbols and Pictographs block
emoji_pattern = re.compile(
    "[\U0001F300-\U0001F9FF"   # Misc symbols and pictographs
    "\U0001FA00-\U0001FA9F"    # Chess symbols
    "\U0001FAA0-\U0001FAFF"    # Symbols and pictographs extended
    "\u2600-\u26FF"             # Misc symbols
    "\u2700-\u27BF"             # Dingbats
    "]+",
    flags=re.UNICODE
)

text = "Hello 🔥 world! ⭐ How are you? 👍"
emojis = emoji_pattern.findall(text)
print(emojis)  # ['🔥', '⭐', '👍']

Removing All Emojis

import re

def remove_emojis(text: str) -> str:
    emoji_pattern = re.compile(
        "[\U0001F600-\U0001F64F"
        "\U0001F300-\U0001F5FF"
        "\U0001F680-\U0001F6FF"
        "\U0001F1E0-\U0001F1FF"
        "\U00002500-\U00002BEF"
        "\U00002702-\U000027B0"
        "\U000024C2-\U0001F251"
        "]+",
        flags=re.UNICODE
    )
    return emoji_pattern.sub("", text)

print(remove_emojis("Hello 🔥 World! 🌍"))  # "Hello  World! "

For production use, the emoji library's approach is more accurate than regex because it uses the actual Unicode emoji list:

import emoji
import re

def remove_emojis_accurate(text: str) -> str:
    return emoji.replace_emoji(text, replace="")

Encoding and Decoding Emojis

When reading from or writing to files, databases, or APIs, you may need to handle encoding explicitly.

Writing Emoji to a File

# Always use UTF-8 when writing files with emoji
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello 🌍\n")
    f.write("Fire: 🔥\n")

# Reading back
with open("output.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

JSON with Emojis

Python's json module handles emojis correctly but escapes them as Unicode by default:

import json

data = {"message": "Hello 🌍", "emoji": "🔥"}

# Default: escapes non-ASCII
json_str = json.dumps(data)
print(json_str)  # {"message": "Hello \ud83c\udf0d", "emoji": "\ud83d\udd25"}

# ensure_ascii=False: keeps literal emoji characters
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)  # {"message": "Hello 🌍", "emoji": "🔥"}

Both are valid JSON — parsers will decode the escaped form back to the emoji character automatically.

Emoji in Django / SQLAlchemy

PostgreSQL handles emoji in UTF-8 columns natively. MySQL requires utf8mb4 character set (the standard utf8 in MySQL only supports 3-byte UTF-8, which can't store most emojis).

# Django: ensure your database uses UTF-8 / utf8mb4
# In settings.py for MySQL:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "OPTIONS": {"charset": "utf8mb4"},
    }
}

For PostgreSQL (the recommended database for emoji support), no special settings are needed.

Practical Examples

Adding Emoji to Log Messages

import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)

logger.info("🚀 Server starting...")
logger.info("✅ Database connected")
logger.warning("⚠️ Rate limit approaching")
logger.error("❌ Payment processing failed")

Emoji-Based Status Output in CLI Tools

def print_status(message: str, status: str) -> None:
    icons = {
        "success": "✅",
        "error": "❌",
        "warning": "⚠️",
        "info": "ℹ️",
        "running": "🔄",
    }
    icon = icons.get(status, "•")
    print(f"{icon} {message}")

print_status("Tests passed", "success")    # ✅ Tests passed
print_status("Build failed", "error")      # ❌ Build failed
print_status("Cache cleared", "info")      # ℹ️ Cache cleared

Explore More on EmojiFYI

เครื่องมือที่เกี่ยวข้อง

⌨️ แป้นพิมพ์ Emoji แป้นพิมพ์ Emoji
เรียกดูและคัดลอก emoji จาก 3,953 ตัวที่จัดตามหมวดหมู่ ใช้งานได้ในทุกเบราว์เซอร์ ไม่ต้องติดตั้ง
🔍 ตัววิเคราะห์ลำดับ ตัววิเคราะห์ลำดับ
ถอดรหัสลำดับ ZWJ, ตัวปรับแต่งสีผิว, ลำดับ keycap และคู่ธงเป็นส่วนประกอบแต่ละชิ้น

คำในอภิธานศัพท์

UTF-8 UTF-8
การเข้ารหัส Unicode แบบความกว้างผันแปร ใช้ 1 ถึง 4 ไบต์ต่ออักขระ เป็นมาตรฐานหลักบนเว็บ (ใช้โดยเว็บไซต์กว่า 98%)
Variation Selector (VS) Variation Selector (VS)
อักขระ Unicode (VS-15 U+FE0E และ VS-16 U+FE0F) ที่กำหนดว่าอักขระจะแสดงผลเป็นข้อความ (สีเดียว) หรืออิโมจิ (มีสี)
Zero Width Joiner (ZWJ) Zero Width Joiner (ZWJ)
อักขระ Unicode ที่มองไม่เห็น (U+200D) ใช้เพื่อเชื่อมอิโมจิหลายตัวเข้าเป็นอิโมจิรวม เช่น การรวมคนและวัตถุเป็นอิโมจิอาชีพ
โค้ดพอยท์ โค้ดพอยท์
ค่าตัวเลขเฉพาะที่กำหนดให้กับอักขระแต่ละตัวในมาตรฐาน Unicode เขียนในรูปแบบ U+XXXX (เช่น U+1F600 สำหรับ 😀)
ตัวปรับโทนผิว ตัวปรับโทนผิว
อักขระตัวปรับแต่ง Unicode ห้าตัวที่อิงตามสเกล Fitzpatrick ใช้เปลี่ยนสีผิวของอิโมจิมนุษย์ (U+1F3FB ถึง U+1F3FF)
ยูนิโค้ด ยูนิโค้ด
มาตรฐานการเข้ารหัสอักขระสากลที่กำหนดหมายเลขเฉพาะให้กับอักขระทุกตัวในทุกระบบการเขียนและชุดสัญลักษณ์ รวมถึงอิโมจิ
อิโมจิ อิโมจิ
คำภาษาญี่ปุ่น (絵文字) แปลว่า 'อักขระภาพ' — สัญลักษณ์กราฟิกขนาดเล็กที่ใช้ในการสื่อสารดิจิทัลเพื่อแสดงความคิด อารมณ์ และวัตถุ

บทความที่เกี่ยวข้อง