Python2.7字符串解码。

2024-06-10 10:55:02 发布

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

在下面的Python2.7shell中,我希望“s.decode('cp437')”和print(s)会给我相同的输出,但是它们不是,这是什么原因呢?在

>>> import sys
>>> sys.stdout.encoding
'cp437'
>>> sys.stdin.encoding
'cp437'
>>>
>>> s = "Flügel"
>>> s
'Fl\x81gel'
>>> s.decode('cp437')
u'Fl\xfcgel'
>>>
>>> print(s)
Flügel
>>>

Tags: importstdinstdoutsys原因shellencodingprint
2条回答

decode返回解码后的值,而不是替换s。在

如果你想改变你的变量

s = s.decode('cp437')

(有趣的是,documentation只是说它解码字符串,而encode documentation声明它返回一个编码字符串)

这不是由str.decode引起的。当您在交互式shell中输入一个对象时,它将打印该对象的表示,而不是对象本身。对于某些类型,如整数,它们显示的是相同的:

>>> i = 42
>>> i
42
>>> print(repr(i))
42
>>> print(i)
42

对于其他类型(如字符串),它们显示两种不同的内容:

^{pr2}$

与Unicode对象类似:

>>> u = s.decode('cp437')
>>> u
u'Fl\xfcgel'
>>> print(repr(u))
u'Fl\xfcgel'
>>> print(u)
Flügel

注意到在字符串和Unicode对象的情况下,对象的表示是实例化它的Python代码,这可能会很有帮助(或令人困惑)。通过使用datetime.datetime的演示,这可能会更清楚,它采用了相同的范例:

>>> d = datetime.datetime(2012, 12, 20, 23, 59, 59)
>>> d
datetime.datetime(2012, 12, 20, 23, 59, 59)
>>> print(repr(d))
datetime.datetime(2012, 12, 20, 23, 59, 59)
>>> print(d)
2012-12-20 23:59:59

相关问题 更多 >