Christopher Tyler

Python tip: name your unicode characters

I got this tip from Trey Hunner’s newsletter. I would highly suggest signing up to his newsletter and looking at Python Morsels. If you use unicode in your code, create a variable instead of trying to use numerical codes:

1
2
3
>>> dashes = "-–﹘—"
>>> print(*dashes)
-   

Instead of this:

1
>>> flair = "\u2728"

Explicitly name Unicode characters

That’s why I prefer to use \N{...} to reference Unicode characters by their name:

1
>>> flair = "\N{sparkles}"

That makes it much easier for me to guess what that character actually represents:

1
2
>>> print(flair)

It works for all Unicode characters, including multi-word names:

1
2
>>> print("\N{waving hand sign}")
👋

How to find a character’s name

Don’t know the name of a Unicode character? Use unicodedata.name to look it up:

1
2
3
4
5
6
7
8
>>> import unicodedata
>>> for c in dashes:
...     print(f"{unicodedata.name(c)}: {c}")
...
HYPHEN-MINUS: -
EN DASH: 
SMALL EM DASH: 
EM DASH: 

You can also do a visual search on utf8.xyz (which Seth Larson started and I now own). Both searching by name (e.g. utf8.xyz/sparkles) or by the character itself (e.g. https://utf8.xyz/—) works.

<< Previous Post

|

Next Post >>

#Trey Hunner #Python #Unicode