gpt4 book ai didi

python - Unicode 转义不适用于用户输入

转载 作者:行者123 更新时间:2023-12-01 01:30:36 24 4
gpt4 key购买 nike

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

为什么会失败?

最佳答案

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

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

关于python - Unicode 转义不适用于用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com