0

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?

2
  • Depending on your use-case, you might want to store the name of the character instead: unicodedata.name('SNAKE') == '🐍'. Commented Feb 16, 2021 at 22:03
  • Which error do you get? Could you edit your question? Commented Feb 17, 2021 at 10:17

2 Answers 2

2

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 = 🐍
Sign up to request clarification or add additional context in comments.

Comments

1

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))
'🐍'

2 Comments

It works this way. However, I’m just curious that is there a way to achieve this using \Ux? I know in shell scripting that you can do something like \U${x}. So I just want to know if python has this feature as well.
\U is part of the syntax for a literal; it's not a lookup function to use with runtime data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.