python:Windows终端中的unicode,使用编码吗?

2024-06-28 21:46:07 发布

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

我在Windows 7终端中使用Python解释器。
我试图用unicode和编码来表达我的想法。

I型:

>>> s='ë'
>>> s
'\x89'
>>> u=u'ë'
>>> u
u'\xeb'

问题1:为什么字符串s中使用的编码与unicode字符串u中使用的编码不同?

我继续,然后键入:

>>> us=unicode(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal
not in range(128)
>>> us=unicode(s, 'latin-1')
>>> us
u'\x89'

问题2:我试着使用latin-1编码来将字符串转换为unicode字符串(实际上,我首先尝试了其他一些编码,包括utf-8)。我怎样才能找到终端用来编码我的字符串的编码?

问题3:如何使终端打印ëë,而不是'\x89'u'xeb'嗯,愚蠢的我。print(s)完成任务。

我已经看了这个相关的问题,但是没有任何线索:Set Python terminal encoding on Windows


Tags: 字符串in终端most编码键入windowsunicode
3条回答

Unicode不是编码。将编码为字节字符串并解码为Unicode:

>>> '\x89'.decode('cp437')
u'\xeb'
>>> u'\xeb'.encode('cp437')
'\x89'
>>> u'\xeb'.encode('utf8')
'\xc3\xab'

windows终端使用DOS的旧代码页。对于我们Windows,它是:

>>> import sys
>>> sys.stdout.encoding
'cp437'

Windows应用程序使用Windows代码页。Python的IDLE将显示windows编码:

>>> import sys
>>> sys.stdout.encoding
'cp1252'

你的结果可能不同。

在从tutorial中阅读本节之后,请通读这篇关于unicode的python HOWTO

在Python中创建Unicode字符串和创建普通字符串一样简单:

>>> u'Hello World !'
u'Hello World !'

要回答您的第一个问题,它们是不同的,因为只有在使用u''时,才创建unicode字符串。

第二个问题:

sys.getdefaultencoding()

返回默认编码

但引用link

Python users who are new to Unicode sometimes are attracted by default encoding returned by sys.getdefaultencoding(). The first thing you should know about default encoding is that you don't need to care about it. Its value should be 'ascii' and it is used when converting byte strings StrIsNotAString to unicode strings.

避开Windows终端

我不想说“终端”更恰当地说“DOS提示”与Windows7一起发布是绝对的垃圾。在Windows 95、NT、XP、Vista和7中都很糟糕。也许他们用Powershell解决了这个问题,我不知道。然而,这表明了当时困扰微软操作系统开发的问题。

输出到文件

设置PYTHONIOENCODING环境变量,然后将输出重定向到文件。

set PYTHONIOENCODING=utf-8

./myscript.py > output.txt

然后使用Notepad++可以看到输出的UTF-8版本。

安装win unicode控制台

win-unicode-console可以解决您的问题。你应该试试

pip install win-unicode-console

如果您对python和命令行输出问题的完整讨论感兴趣,请签出Python issue 1602。否则,只需使用win unicode控制台包。

py -m run script.py

在每个脚本中运行它,或者通过将其添加到usercustomizesitecustomize,您可以按照它们的指示将win_unicode_console.enable()添加到每个调用中。

相关问题 更多 >