Python: Unicode Escape Sequence

By Xah Lee. Date: . Last updated: .

Both python 3 and python 2 can have Unicode characters literally in String . For example, u"i ♥ u" .

You can also use escape sequences. There are the following forms:

\u4_digits_hex
For a char whose unicode codepoint can be expressed in 4 hexadecimal decimals. If less than 4 digits, add 0 in front.
\U8_digits_hex
For a char whose unicode codepoint is more than 4 hexadecimal decimals. If the char's hexadecimal digits is less than 8 digits, you must add 0 in front to make a total of 8 digits.
\N{name}
Unicode character named name

(To find a unicode's codepoint and name, see Unicode Search 😄)

import sys
print(sys.version)

# BLACK HEART SUIT, hexadecimal 2665
print("♥" == "\u2665")

# GRINNING CAT FACE WITH SMILING EYES, hexadecimal 1f638
print("😸" == "\U0001f638")

# BLACK HEART SUIT, hexadecimal 2665
print("♥" == "\N{BLACK HEART SUIT}")
# -*- coding: utf-8 -*-
# python 2

import sys
print(sys.version)

# BLACK HEART SUIT, hexadecimal 2665
print u"♥" == u"\u2665"

# GRINNING CAT FACE WITH SMILING EYES, hexadecimal 1f638
print (u"😸" == u"\U0001f638")

# BLACK HEART SUIT, hexadecimal 2665
print (u"♥" == u"\N{BLACK HEART SUIT}")

Python Unicode

Python

Overview

Help

Comment

String

Arithmetic

Boolean

Conditional

Loop, Iteration

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc