python - 为什么Python中的字符串在列表内部和外部显示不同?

标签 python string encoding

我正在抓取一个网页,我猜得到的是一个 utf-8 文本。因此,发生了以下情况:

# -*- coding: utf-8 -*-
import urllib2
import json

url = '....'
data = json.load(urllib2.urlopen(url))
a = u'\u0391\u0391\u039b\u0395\u039d'
print a
ΑΑΛΕΝ
print [a]
[u'\u0391\u0391\u039b\u0395\u039d']

有什么想法为什么第二次不显示为第一次吗?

最佳答案

print 对参数隐式调用 str,但对于列表,str 对所有参数调用 repr内部元素。例如:

>>> class Foo(object):
...     def __str__(self):
...         return 'world'
...     def __repr__(self):
...         return 'hello'
... 
>>> f = Foo()
>>> print repr(f)
hello
>>> print f
world
>>> print [f]
[hello]

关于python - 为什么Python中的字符串在列表内部和外部显示不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419048/

相关文章:

python - 我怎样才能将 Lua 嵌入到 Python 3.x 中?

c - 生成 10 个随机字符

c++ - 识别字符串中的字符

vim - 在 Vim 中将编码和文件编码设置为 utf-8

python - csv writer 在每一行周围加上引号

python - 如何在 TensorFlow 中获取张量中元素的计数?

java - Java 中的紧凑图像编码

mysql - 续集永远不会返回 utf-8,只是 ascii-8bit

python - QtWidgets.QApplication(sys.argv) 后无法导入 PyQt 模块

java - 同时按空格、点和逗号分割字符串