Unicode转义不适用于用户inpu

2024-04-26 11:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

为什么会失败?你知道吗


Tags: ofthe用户脚本密码numberinput错误
1条回答
网友
1楼 · 发布于 2024-04-26 11:35:33

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

相关问题 更多 >