JackeyOL
JackeyOL

Reputation: 321

Type unicode character using python variable

The code point of '🐍' in hex is '0001f40d', and I store this code point in variable hex_snake. Then I want to call this icon using '\Uhex_snake' but got an error. Any ideas on expanding variables inside of quotes?

Upvotes: 0

Views: 219

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177901

The \U escape code can only be used in string literals, and must be followed by eight hexadecimal digits between 00000000-0010FFFF. But you can just store the character in your variable instead and print with f-strings:

>>> snake = '\U0001f40d'  # or '\N{SNAKE}' or chr(0x1f40d)
>>> print(f'snake = {snake}')
snake = 🐍

If you have hex digits in a string and don't want to change, the following works, but is more complicated:

>>> snake = '0001f40d'
>>> print(f'snake = {chr(int(snake,16))}')
snake = 🐍

Upvotes: 1

chepner
chepner

Reputation: 531858

The given string can be turned into an int, which can then be used as an argument for chr.

>>> x = '0001f40d'
>>> chr(int(x, base=16))
'🐍'

Upvotes: 1

Related Questions