打印时Python呈现unicode代码

2024-07-03 07:00:31 发布

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

Elasticsearch返回了一个字符串:

\n\nESM Management LLC (\u201cESM\u201d) provides investment

当我打印字符串时,字符串的表示方式与上图完全相同。 我试过解码,也就是s.decode('utf8'),但我认为编码/解码过程中有一些基本的东西我不了解。你知道吗

如何转换此字符串,以便呈现新行,并将unicode代码转换为它们所表示的符号?你知道吗

这就是我要找的:

.>>> s = '\n\nESM Management LLC (\u201cESM\u201d) provides investment'
.>>> s
.
.
.ESM Management LLC ("ESM") provides investment 

Tags: 字符串编码方式utf8elasticsearch解码managementprovides
1条回答
网友
1楼 · 发布于 2024-07-03 07:00:31

看起来您正在使用Python2。你知道吗

  1. 对这样的文字使用unicode。你知道吗
  2. 编码为标准输出编码以确保正确打印。你知道吗

-

import sys

s = u'\n\nESM Management LLC (\u201cESM\u201d) provides investment'
print s.encode(sys.stdout.encoding)


ESM Management LLC (“ESM”) provides investment

如果正如你在底部所说的,它是一个来自其他地方的字节字符串,那么你不能使用unicode文本。改为使用“unicode scape”解码。你知道吗

s = '\n\nESM Management LLC (\u201cESM\u201d) provides investment'
print s.decode(encoding='unicode-escape').encode(sys.stdout.encoding)


ESM Management LLC (“ESM”) provides investment

编辑正如@wim在注释中解释的,编码为sys.stdout.encoding可能是不需要的,因为print无论如何都会这样做。根据终端和shell编码的不同,可能需要额外的解码,但我不确定到底应该做什么。因此,我将保留原样的答案,因为它有助于操作。有关此主题的更多信息,请参见this excelent answer。你知道吗

相关问题 更多 >