win10上python编码的问题的思考

由于第一编程语言是java 对python的学习过程中最常遇到的问题是编码问题,一直很头疼,于是查阅了很多资料,总算形成了一点自己的见解,python的环境在 linux 和 win10 上默认编码是不同的,win10上默认编码为 ascii ,linux 上默认编码为 utf-8 ,但是基础编码都是 unicode ,在 win10 环境中进行验证 如下:

常用工具:

1,获取当前系统的默认编码方式

import sys;sys.getdefaultencoding() 

PS C:\Users\jiangcheng> python
Python 2.7.15 |Anaconda, Inc.| (default, May  1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> sys.getdefaultencoding()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> sys.getfilesystemencoding()
'mbcs'
>>> sys.stdin.encoding()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> sys.stdin.encoding
'cp936'
>>> sys.stdout.encoding
'cp936'

2,获取当前变量的编码方式

import chardet;chardet.detect(a)

>>> a = "中国"
>>> import chardec
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named chardec
>>> import chardet
>>> chardet.detect(a)
{'confidence': 0.7679697235616183, 'language': 'Russian', 'encoding': 'IBM855'}
>>> b = "jiangcheng"
>>> chardet.detect(b)
{'confidence': 1.0, 'language': '', 'encoding': 'ascii'}
>>> print a
中国
>>> a.decode("gbk")
u'\u4e2d\u56fd'
>>> a_gbk = a.decode("gbk")
>>> print a_gbk
中国
>>> a_utf-8 = a_gbk.encode("utf-8")
  File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> type(a_gbk)
<type 'unicode'>
>>> print a_gbk.encode('UTF-8')
涓浗
>>> a_utf-8 = a_gbk.encode('UTF-8')
  File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> print a_gbk.encode('UTF-8')
涓浗
>>> a_utf8 = a_gbk.encode('UTF-8')
>>> print a_utf8
涓浗

3,改变编码 utf-8 到 gbk 方式可以先 decode(“utf-8”)得到 unicode 编码方式的结果 然后 encode(“gbk”)就可以转变成 目标编码方式的结果

>>> a_utf8
'\xe4\xb8\xad\xe5\x9b\xbd'
>>> a_utf8.decode('UTF-8')
u'\u4e2d\u56fd'
>>> print a_utf8.decode('UTF-8')
中国
>>> chardet.detect(a_utf8)
{'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'}
>>> a_unicode = a_utf8.decode('utf-8')
>>> a_unicode
u'\u4e2d\u56fd'
>>> print a_unicode
中国
>>> a_gbk = a_unicode.encode('gbk')
>>> a_gbk
'\xd6\xd0\xb9\xfa'
>>> print a_gbk
中国
>>> type(a_gbk)
<type 'str'>
>>>

在win10上默认编码方式为 gbk 因此 unicode编码方式的变量 直接打印时 输出结果转换为 gbk 编码方式显示 ,如果既不是 unicode 编码方式 也没有手动转变为 gbk 编码方式 直接打印就会生成乱码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值