字符串编码格式查看和转换

By 水木神風 at 2017-08-07 • 0人收藏 • 2369人看过


import chardet  

s = '哈哈哈我就是一段测试的汉字呀'  

print chardet.detect(s) 


输出:{'confidence': 0.99, 'encoding': 'utf-8'}


unicode是一种二进制编码,所有的utf-8和gbk编码都得通过unicode编码进行转译,说的直白一点,utf-8和gbk编码之间不能之间转换,要在unicode之间过个场才能转换。下面我图解一下,方便理解:



各种编码之间如何转换

Python中有两个很好用的函数 decode() 和 encode()

decode(‘utf-8’) 是从utf-8编码转换成unicode编码,当然括号里也可以写'gbk'

encode('gbk') 是将unicode编码编译成gbk编码,当然括号里也可以写'utf-8'

假如我知道一串编码是用utf-8编写的,怎么转成gbk呢


[python] view plain copy

  1. s.decode('utf-8').encode('gbk')  

像上面这样就可以了


图解一下:


1 个回复 | 最后更新于 2017-08-22
2017-08-22   #1

#控制台输出编码后带中文的uri

import urllib

print urllib.unquote(a).decode('utf-8').encode('gbk')

登录后方可回帖