简体   繁体   中英

Python 3: How can I take a value in a variable and convert that to a unicode character?

I'm trying to take a value and turn it into a unicode character, either by name or by value. Every example I've seen has values hard-coded into the strings (like q = '\쎨') but that's not really helpful for me. I'm getting some numerical or literal name input into variables. I just can't figure out how to make it go. I've tried various iterations of encode, decode, eval, r-strings, f-string, and I've got nothing. What am I missing? This is in Python 3.10.

LATIN_SMALL_LETTER_E_WITH_GRAVE = 0xC3A8
j = LATIN_SMALL_LETTER_E_WITH_GRAVE
print (j, "\u%04x" % j)

However, when I run it, I get this:

    print (j, "\u%04x" % j)
                       ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

Similarly, if I do something like this:

char_name = "LATIN SMALL LETTER E WITH GRAVE"
z = "\N{" + char_name + "}"

I get this:

    z = "\N{" + char_name + "}"
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: malformed \N character escape

Here is my attempt, which may be helpful for you. If you take the number after the hexadecimal indicator '0x' which is C3A8, you can display the information about the Unicode character in the following way:

import unicodedata


def unicode_test(value):
    import unicodedata
    name = unicodedata.name(value)
    value2 = unicodedata.lookup(name)

    print('value="%s", name="%s", value2 = "%s"' % (value, name, value2))
    return value


character_wanted = unicode_test('\uC3A8')

Output:

value="쎨", name="HANGUL SYLLABLE SSYEOL", value2 = "쎨"

Of course, what the comments are suggesting you do above using the chr method is completely correct as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM