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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fancychuan/article/details/78647066

上周在做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'

使用的时候注意分辨。

猜你喜欢

转载自blog.csdn.net/fancychuan/article/details/78647066