Search code examples
pythonunicode-escapes

Unicode escape not working with user input


I have a short python script that's supposed to print the unicode character from a number the user inputs. However, it's giving me an error.

Here's my code:

print("\u" + int(input("Please enter the number of a unicode character: ")))

It's giving me this error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 0-1: truncated \uXXXX escape

Why does this fail?


Solution

  • You'll want to unicode_escape the string itself:

    input_int = int(input("Please enter the number of a unicode character: "))
    # note that the `r` here prevents the `SyntaxError` you're seeing here
    # `r` is for "raw string" in that it doesn't interpret escape sequences
    # but allows literal backslashes
    escaped_str = r"\u{}".format(input_int)  # or `rf'\u{input_int}'` py36+
    import codecs
    print(codecs.decode(escaped_str, 'unicode-escape'))
    

    A sample session:

    >>> input_int = int(input("Please enter the number of a unicode character: "))
    Please enter the number of a unicode character: 2603
    >>> escaped_str = r"\u{}".format(input_int)  # or `rf'\u{input_int}'` py36+
    >>> import codecs
    >>> print(codecs.decode(escaped_str, 'unicode-escape'))
    ☃