Unicode 转义不适用于用户输入
Unicode escape not working with user input
我有一个简短的 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'))
示例会话:
>>> 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 字符。但是,它给了我一个错误。
这是我的代码:
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'))
示例会话:
>>> 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'))
☃