背景
我使用的是 Windows 机器。我知道不再支持 Python 2.*,但我仍在学习 Python 2.7.16。我还有Python 3.7.1。我知道Python 3.*"unicode被重命名为str" https://stackoverflow.com/a/18034409/1175496
我使用 Git Bash 作为我的主 shell。
I read 这个问题 https://stackoverflow.com/questions/18034272/python-str-vs-unicode-types。我觉得我理解 Unicode(代码点)和编码(不同的编码系统;字节)之间的区别。
Question
- 当我评价时
'á'
,我期望得到'\xc3\xa1'
如这个答案所示 https://stackoverflow.com/a/49138962/1175496
- 当我评价时
len('á')
,我期望得到2
, 如这个答案所示 https://stackoverflow.com/a/18034409/1175496
但我没有得到预期的结果。
运行 git bash C:\Python27\python.exe 时...:
Python 2.7.16 (v2.7.16:413a49145e, Mar 4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
>>> 'á'
'\xa0'
#'\xc3\xa1' expected
>>> len('á')
1
#2 expected
# one more for reference:
>>> 'à'
'\x85'
#'\xc3\xa0' expected
您能帮我理解为什么我会得到上面显示的输出吗?
具体为什么'á'
become '\xa0'
?
我尝试过的
我可以用unicode
对象得到我期望的结果:
>>> u'á'.encode('utf-8')
'\xc3\xa1'
>>> len(u'á'.encode('utf-8'))
2
我可以打开IDLE我得到了不同的结果——不是expected结果,但至少我理解这些结果。
Python 2.7.16 (v2.7.16:413a49145e, Mar 4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
>>> 'á'
'\xe1'
>>> len('á')
1
>>> 'à'
'\xe0'
IDLE结果出乎意料,但我仍然理解结果;马丁·彼得斯解释 https://stackoverflow.com/questions/18034272/python-str-vs-unicode-types#comment26380927_18034277 why 'á'
become '\xe1'
采用拉丁 1 编码.
那么,为什么 IDLE 会给出与直接运行 Git Bash Python 2.7.1 可执行文件不同的结果呢?换句话说,如果 IDLE 为使用拉丁语 1对我的输入进行编码,我的 Git Bash Python 2.7.1 使用什么编码。可执行,这样'á'
变成'\xa0'
我想知道什么
是我的默认编码有问题吗?我太害怕了更改默认编码。 https://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console#comment36374776_2013263
>>> import sys; sys.getdefaultencoding()
'ascii'
我感觉这是我的终端的编码有问题吗? (我使用 git bash)我应该尝试吗改变PYTHONIOENCODING环境变量 https://stackoverflow.com/a/32176732/1175496?
我尝试检查一下git bashlocale https://stackoverflow.com/a/36692549/1175496,结果是:
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=
另外,我正在使用交互式 Python ,我应该尝试使用这个文件吗?
# -*- coding: utf-8 -*- sets the source file's encoding, not the output encoding.
I know 升级到Python 3是一个解决方案。 https://stackoverflow.com/a/4637795/1175496,但我仍然好奇为什么我的 Python 2.7.16 的行为有所不同。