python:Windows 终端中的 unicode,使用编码? [英] python: unicode in Windows terminal, encoding used?
问题描述
我在 Windows 7 终端中使用 Python 解释器.
我正在努力解决 unicode 和编码问题.
我输入:
<预><代码>>>>s='ë'>>>秒'x89'>>>u=u'ë'>>>你你'xeb'问题 1:为什么字符串 s
中使用的编码与 unicode 字符串 u
中使用的不同?
我继续,然后输入:
<预><代码>>>>我们=unicode(s)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0: ordinal 中的字节 0x89不在范围内(128)>>>us=unicode(s, 'latin-1')>>>我们你'x89'问题 2:我尝试使用 latin-1
编码,祝你好运,将字符串转换为 unicode 字符串(实际上,我首先尝试了其他一些字符串,包括 utf-8
).如何找出终端使用哪种编码对我的字符串进行编码?
问题 3:如何让终端将 嗯,愚蠢的我.ë
打印为 ë
而不是 'x89'
还是 u'xeb'
?print(s)
完成这项工作.
我已经看过这个相关的 SO 问题,但没有任何线索:设置 PythonWindows 上的终端编码
Unicode 不是一种编码.您编码为字节字符串并解码为 Unicode:
<预><代码>>>>'x89'.decode('cp437')你'xeb'>>>u'xeb'.encode('cp437')'x89'>>>u'xeb'.encode('utf8')'xc3xab'Windows 终端使用 DOS 的旧代码页.对于美国 Windows,它是:
<预><代码>>>>导入系统>>>sys.stdout.encoding'cp437'Windows 应用程序使用 Windows 代码页.Python 的 IDLE 将显示 windows 编码:
<预><代码>>>>导入系统>>>sys.stdout.encoding'cp1252'您的结果可能会有所不同.
I am using the Python interpreter in Windows 7 terminal.
I am trying to wrap my head around unicode and encodings.
I type:
>>> s='ë'
>>> s
'x89'
>>> u=u'ë'
>>> u
u'xeb'
Question 1: Why is the encoding used in the string s
different from the one used in the unicode string u
?
I continue, and type:
>>> 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'
Question2: I tried using the latin-1
encoding on good luck to turn the string into an unicode string (actually, I tried a bunch of other ones first, including utf-8
). How can I find out which encoding the terminal has used to encode my string?
Question 3: how can I make the terminal print Hmm, stupid me. ë
as ë
instead of 'x89'
or u'xeb'
?print(s)
does the job.
I already looked at this related SO question, but no clues from there: Set Python terminal encoding on Windows
Unicode is not an encoding. You encode into byte strings and decode into Unicode:
>>> 'x89'.decode('cp437')
u'xeb'
>>> u'xeb'.encode('cp437')
'x89'
>>> u'xeb'.encode('utf8')
'xc3xab'
The windows terminal uses legacy code pages for DOS. For US Windows it is:
>>> import sys
>>> sys.stdout.encoding
'cp437'
Windows applications use windows code pages. Python's IDLE will show the windows encoding:
>>> import sys
>>> sys.stdout.encoding
'cp1252'
Your results may vary.
这篇关于python:Windows 终端中的 unicode,使用编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!