【问题标题】:Python list items encodingPython列表项编码
【发布时间】:2016-04-18 15:44:12
【问题描述】:

为什么在 Python 2.7 中当我遍历列表项时编码会发生变化?

test_list = ['Hafst\xc3\xa4tter', 'asbds@ages.at']

打印列表:

print(test_list)

得到这个输出:

['Hafst\xc3\xa4tter', 'asbds@ages.at']

到目前为止,一切都很好。但是为什么会这样,当我遍历列表时,例如:

for item in test_list:
    print(item)

我得到这个输出:

Hafstätter
asbds@ages.at

为什么编码会改变(是吗??我怎样才能改变编码在列表中

【问题讨论】:

标签: python list unicode encoding


【解决方案1】:

编码没有改变,它们只是显示字符串的不同方式。一个将非 ASCII 字节显示为用于调试的转义码:

>>> test_list = ['Hafst\xc3\xa4tter', 'asbds@ages.at']
>>> print(test_list)
['Hafst\xc3\xa4tter', 'asbds@ages.at']
>>> for item in test_list:
...     print(item)
...     
Hafstätter
asbds@ages.at

但它们是等价的:

>>> 'Hafst\xc3\xa4tter' == 'Hafstätter'
True

如果您想查看与非调试输出一起显示的列表,您必须自己生成它:

>>> print("['"+"', '".join(item for item in test_list) + "']")
['Hafstätter', 'asbds@ages.at']

调试输出有原因:

>>> a = 'a\xcc\x88'
>>> b = '\xc3\xa4'
>>> a
'a\xcc\x88'
>>> print a,b   # should look the same, if not it is the browser's fault :)
ä ä
>>> a==b
False
>>> [a,b]      # In a list you can see the difference by default.
['a\xcc\x88', '\xc3\xa4']

【讨论】:

  • 我觉得这个话题真的很难,所以非常感谢您的澄清!谢谢!!
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 2016-06-16
  • 2015-02-27
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多