您的位置:首页 > 编程语言 > Python开发

python在不同系统下的中文编码问题

2017-11-27 17:19 633 查看
上周在做QQ邮箱的模拟登录,在调用邮件查找接口的时候,遇到了查询字符串下中文编码的问题,本质是python2环境下中文编码的问题。

Windows

Windows下通过CMD打开python终端,默认的编码方式是gbk。

C:\Windows\System32>python
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.
1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org >>> '招商'
'\xd5\xd0\xc9\xcc'
>>> type('招商')
<type 'str'>
>>> '招商'.decode('gbk')
u'\u62db\u5546'
>>> u'招商'
>u'\u62db\u5546'
>>>> '招商'.decode('gbk').encode('gbk')
'\xd5\xd0\xc9\xcc'


如果直接打开anaconda下的ipython或者python,默认的编码方式是utf-8

In [1]: '招商'
Out[1]: '\xe6\x8b\x9b\xe5\x95\x86'

In [2]: '招商'.decode('utf-8')
Out[2]: u'\u62db\u5546'

In [3]: u'招商'
Out[3]: u'\u62db\u5546'


因此,如果是使用anaconda,那么在py文件中的中文会被utf8编码存储,除非显性写成 u’中文’,然后进行编码。

Linux

linux 下的python默认编码方式为utf-8

[root@iZm5eapte3nlp363mzinz8Z ~]# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> '招商'
'\xe6\x8b\x9b\xe5\x95\x86'
>>> '招商'.decode('utf-8')
u'\u62db\u5546'
>>> '招商'.decode('utf-8').encode('gbk')
'\xd5\xd0\xc9\xcc'


使用的时候注意分辨。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: