代码之家  ›  专栏  ›  技术社区  ›  Picachieu

Unicode转义不使用用户输入

  •  1
  • Picachieu  · 技术社区  · 6 年前

    我有一个简短的python脚本,它应该从用户输入的数字中打印unicode字符。但是,它给了我一个错误。

    以下是我的代码:

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

    它给了我这个错误:

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

    为什么失败了?

    1 回复  |  直到 6 年前
        1
  •  2
  •   anthony sottile    6 年前

    你会想要 unicode_escape 字符串本身:

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

    示例会话:

    >>> 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'))
    ☃
    
    推荐文章