Unicode转义不适用于用户输入

时间:2018-10-21 04:11:00

标签: python unicode-escapes

我有一个简短的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 个答案:

答案 0 :(得分:2)

您将要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'))
☃