python2之字符编码案例分析(1)

1.先看代码

#coding=utf-8  
(当你不指定编码格式,系统默认编码是ascii,
意味着如果你的py文件中有中文,那么运行会报错)
def a(local):
        print(type(local))
        print("hahaha哈哈哈",local)
if __name__ == "__main__":
        print(sys.getdefaultencoding())
        localPath = r'D:\测量任务\故障定位工具\code\1.1使用正则下载一个目录下的多个文件.txt'
        print(chardet.detect(localPath))
        print(localPath)
        a(localPath)

运行结果:

ascii ——(系统默认的编码是ascii)
{‘confidence’: 0.99, ‘language’: ”, ‘encoding’: ‘utf-8’}——字符localPath 的编码是utf-8?为什么,因为我在开头告诉python解释器,使用utf-8读取此py文件
D:\测量任务\故障定位工具\code\1.1使用正则下载一个目录下的多个文件.txt
< type ‘str’ >
(‘hahaha\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88’, ‘D:\\xe6\xb5\x8b\xe9\x87\x8f\xe4\xbb\xbb\xe5\x8a\xa1\\xe6\x95\x85\xe9\x9a\x9c\xe5\xae\x9a\xe4\xbd\x8d\xe5\xb7\xa5\xe5\x85\xb7\code\1.1\xe4\xbd\xbf\xe7\x94\xa8\xe6\xad\xa3\xe5\x88\x99\xe4\xb8\x8b\xe8\xbd\xbd\xe4\xb8\x80\xe4\xb8\xaa\xe7\x9b\xae\xe5\xbd\x95\xe4\xb8\x8b\xe7\x9a\x84\xe5\xa4\x9a\xe4\xb8\xaa\xe6\x96\x87\xe4\xbb\xb6.txt’)


为什么以utf-8字符打印出来?我的中文呢?

2.查资料

https://blog.csdn.net/apache0554/article/details/53889253
彻底搞懂Python的字符编码
https://www.cnblogs.com/zihe/p/6993891.html
Python(字符编码)

所学知识:

python的encode可以将unicode编码转换为utf-8或者gbk
decode可以就将utf-8或者gbk转换为unicode
注意,utf-8不能直接转为gbk,只能先到Unicode,再从Unicode到gbk

#coding=utf-8
str1 = '中文'  #(这是utf-8的str)
str2 = str1.decode('utf-8')  #将utf-8编码的str1转换为Unicode类型的字符串
#str2的<type 'unicode'>
str2.encode('gbk')  #将Unicode字符转换为gbk编码的str

https://www.cnblogs.com/litaozijin/p/6416133.html
【原创】python中文编码问题深入分析(二):print打印中文异常及显示乱码问题分析与解决

打印乱码可能有两个原因:

1.如果变量是Unicode类型,控制台会将此变量转换为系统自带的编码,从而输出中文。
但是,如果系统编码是ascii呢?使用sys.stdout.encoding查看。
所以你可以将Unicode转换为utf-8或者gbk然后输出,当然,转换那种编码,需要与你的系统编码一致。
2.py使用的编码和系统的编码不一致,很抱歉,不是报错就是乱码。
比如py用gbk,但是系统是utf-8,哦,乱码了。

3.解决问题

我的问题根源并不是编码,而是print()
当我将‘,’替换为‘+’,哦,世界清净了。
为什么?
不知道。等我知道了再来更新吧。

猜你喜欢

转载自blog.csdn.net/qq_29778641/article/details/82153956