Python 打印带有 unicode 转义字符的字符串

Python print string with unicode escape characters

我正在尝试打印“Pedro Le\u00F3n”的文字 unicode 转义字符。当我执行以下操作时:

test = "Pedro Le\u00F3n"
print(test)

>>> Pedro León

如何让它输出“Pedro Le\u00F3n”?

试试这个

test = "Pedro Le\u00F3n"
print(test)

它的原因是因为在 python 中有许多“特殊字符,如” '\n' 等等,如果你想忽略它,你需要写 \ 而不是 \

您需要使用原始字符串。只需在字符串前使用 r

test = r"Pedro Le\u00F3n"
print(test)

输出:Pedro Le\u00F3n

使用 unicode_escape encoding 编码为字节,然后立即解码:

>>> out = test.encode('unicode_escape').decode()
>>> out
'Pedro Le\xf3n'
>>> print(out)
Pedro Le\xf3n

请注意,它是 \xXX 转义而不是 \uXXXX 转义,因为它小于 U+FF。比较:

>>> '\u0080'
'\x80'