如何从unicode中打印正确的字符,如\\u201c和x501F\\u201d和x4E1C风&引用;在python 3中?

如何从unicode中打印正确的字符,如\\u201c和x501F\\u201d和x4E1C风&引用;在python 3中?,python,python-3.x,unicode,Python,Python 3.x,Unicode,它在控制台上打印“唸é 您没有正确转义字符,您有一个额外的\: # coding=utf-8 import codecs str_unicode = "\\u201c借\\u201d东风" str_bytes = codecs.decode(str_unicode, 'unicode-escape') print(str_bytes) Unicode标准包含许多列出字符及其对应代码点的表格: >>> print("\u201c借\u201d东风") “借”东风 006

它在控制台上打印“唸é

您没有正确转义字符,您有一个额外的
\

# coding=utf-8
import codecs

str_unicode = "\\u201c借\\u201d东风"
str_bytes = codecs.decode(str_unicode, 'unicode-escape')
print(str_bytes)

Unicode标准包含许多列出字符及其对应代码点的表格:

>>> print("\u201c借\u201d东风")
“借”东风
0061'a';拉丁文小写字母A
0062‘b’;拉丁文小写字母B
0063‘c’;拉丁文小写字母C
...
007B'{';左花括号
...
2167‘Ⅶ’:罗马数字8
2168‘Ⅸ’:罗马数字九
...
265E'♞': 黑棋骑士
265F'♟': 黑棋棋子
...

1F600'Francisco Couzo正确地描述了您的问题。如果您可以控制字符串,则应避免转义Unicode字符串中的引号字符。但我猜您实际上并不是将该字符串作为文本编写的,而是从外部源(如文件)获取的

如果Unicode字符串中已包含额外的转义字符,则可以通过先对数据进行编码(使用
str.encode
),然后从已编码的字符中去除额外的反斜杠,然后再次解码来解决此问题:

0061    'a'; LATIN SMALL LETTER A
0062    'b'; LATIN SMALL LETTER B
0063    'c'; LATIN SMALL LETTER C
...
007B    '{'; LEFT CURLY BRACKET
...
2167    'Ⅶ': ROMAN NUMERAL EIGHT
2168    'Ⅸ': ROMAN NUMERAL NINE
...
265E    '♞': BLACK CHESS KNIGHT
265F    '♟': BLACK CHESS PAWN
...
1F600   'Francisco Couzo correctly describes your issue. If you have control of the string, you should avoid escaping the quotation mark characters in your Unicode string. But I'm guessing that you didn't actually write that string yourself as a literal, but rather, you got it from external source (like a file).

If your Unicode string already has the extra escape characters in it, you can fix the problem by first encoding your data (using
str.encode
), then stripping the extra backslashes from the already encoded characters, then finally decoding again:

str_unicode = "\\u201c借\\u201d东风"  # or somefile.read(), or whatever

fixed = str_unicode.encode('unicode-escape').replace(b'\\\\', b'\\').decode('unicode-escape')

print(fixed)  # prints “借”东风

你想打印什么?你的预期输出是什么?@Adam Smith,预期输出是“借”东风这似乎根本没有回答人们提出的问题。仅仅链接到Python文档还远远不够。我知道unicode\u201c的意思是“和\u201d的意思”,但我必须使这些unicode在控制台中打印正确的字符。因此,你的答案没有帮助。但无论如何,谢谢。谢谢,你的解决方案有效。你的猜测是对的,我使用Extract图像元数据到json文件,然后我从这个json文件中获得str_unicode。@GoTop:我很高兴这个答案对你有用。如果你认为它是最好的answe你的问题,请考虑。是的,手动删除“\”工作,但我必须在Python脚本中这样做。