下面介绍一下python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1等编码之间的转换。

1.自动识别字符串编码:

#coding:utf8
#chartdet官方下载网站:http://pypi.python.org/pypi/chardet
import urllib
import chardet
rawdata = urllib.urlopen('http://www.google.cn/').read()
print chardet.detect(rawdata)
 
输出:
#confidence是可信度,encoding是编码
{'confidence': 0.99, 'encoding': 'utf-8'}
 
2.unicode转换为其他编码
 
#coding:utf8
a = u'中文'
a_gb2312 = a.encode('gb2312')
print a_gb2312
 
输出:
  中文
 
3.其他编码转换为unicode
 
#coding:utf8
a = u'中文'
a_gb2312 = a.encode('gb2312')
print a_gb2312
#a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312')
#如果下面不加【】的话,输出结果仍然是:中文
print [unicode(a_gb2312,'gb2312')]
print [a_gb2312.decode('gb2312')]
 
输出:
中文
[u'\u4e2d\u6587']
[u'\u4e2d\u6587']
 
4.非unicode编码之间的相互转化
 
#coding:utf8
a = u'中文'
a_gb2312 = a.encode('gb2312')
print a_gb2312
#编码1转换为编码2可以先转为unicode再转为编码2
a_unicode = a_gb2312.decode('gb2312')
print [a_unicode]
a_utf8 = a_unicode.encode('utf8')
#dos不识别utf8编码,直接输出会是乱码
print [a_utf8]
 
输出:
中文
[u'\u4e2d\u6587']
['\xe4\xb8\xad\xe6\x96\x87']
 
5.判断字符串编码
 
#coding:utf8
#isinstance(s, str) 用来判断是否为一般字符串 
#isinstance(s, unicode) 用来判断是否为unicode 3
#如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错) 
def u(s,encoding):
    if isinstance(s,unicode):
        return s
    else:
        return unicode(s,encoding)
 
6.汉字转化为unicode编码
 
#coding:utf8
#该方法没看懂,先留下了
name = '中国' 
name = name.decode('utf8')
print name
tmpname = ""
 
for c in name:
    c = "%%u%04X" % ord(c)
    tmpname += c 
print tmpname
 
输出结果:
 
中国
%u4E2D%u56FD

python编码(一)的更多相关文章

  1. (转载) 浅谈python编码处理

    最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: UnicodeEncodeError: ...

  2. Python 编码简单说

    先说说什么是编码. 编码(encoding)就是把一个字符映射到计算机底层使用的二进制码.编码方案(encoding scheme)规定了字符串是如何编码的. python编码,其实就是对python ...

  3. Python之路3【知识点】白话Python编码和文件操作

    Python文件头部模板 先说个小知识点:如何在创建文件的时候自动添加文件的头部信息! 通过:file--settings 每次都通过file--setings打开设置页面太麻烦了!可以通过:View ...

  4. python编码规范

    python编码规范 文件及目录规范 文件保存为 utf-8 格式. 程序首行必须为编码声明:# -*- coding:utf-8 -*- 文件名全部小写. 代码风格 空格 设置用空格符替换TAB符. ...

  5. 【转】python编码的问题

    摘要: 为了在源代码中支持非ASCII字符,必须在源文件的第一行或者第二行显示地指定编码格式: # coding=utf-8 或者是: #!/usr/bin/python # -*- coding: ...

  6. 【转】python编码规范

    http://blog.csdn.net/willhuo/article/details/49300441 决定开始Python之路了,利用业余时间,争取更深入学习Python.编程语言不是艺术,而是 ...

  7. python 编码 UnicodeDecodeError

    将一个py脚本从Centos转到win运行,出错如下: UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: il ...

  8. Python编码/文件读取/多线程

    Python编码/文件读取/多线程 个人笔记~~记录才有成长   编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...

  9. 关于Python编码,超诡异的,我也是醉了

    Python的编码问题,真是让人醉了.最近碰到的问题还真不少.比如中文文件名.csv .python对外呈现不一致啊,感觉好不公平. 没图说个JB,下面立马上图.   我早些时候的其他脚本,csv都是 ...

  10. 规范的python编码

    规范的 python 编码令人赏心悦目,令代码的表达逻辑更清晰,使得工程代码更容易被维护和交流: 编码规范包括对于代码书写格式的约束,不良语法的禁用和推荐的编码手法,下面做些简要的描述: 1. 代码规 ...

随机推荐

  1. liblas 1.8.1编译安装

    liblas https://github.com/libLAS/libLAS/issues/102 https://liblas.org/start.html 源码 https://github.c ...

  2. spring ioc 注解配置

    要注意spring 版本与jdk的兼容性 applicationContext-resource.xml: <beans xmlns="http://www.springframewo ...

  3. golang获取IP地址

    ip:=this.Ctx.Request.RemoteAddr ip=ip[0:strings.LastIndex(ip, ":")]

  4. numpy.unpackbits()

    numpy.unpackbits numpy.unpackbits(myarray, axis=None) Unpacks elements of a uint8 array into a binar ...

  5. tortoise svn 请求的名称有效,但是找不到请求的类型的数据

    可能是博客园出bug了,现在无法放图,间断重复刷新十多次依然如故,弃之 这个问题是在安装完svn服务器(visual svn)后复制url,tortoise svn import 粘贴url后 出现的 ...

  6. [leetcode]689. Maximum Sum of 3 Non-Overlapping Subarrays三个非重叠子数组的最大和

    In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...

  7. 7-掉馅饼(数组dp)

    /*                                             免费馅饼 时间限制:1000 ms  |  内存限制:65535 KB                   ...

  8. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  9. 简单的几个Boost定时器

    boost的asio库里有几个定时的器,老的有 deadline_timer , 还有三个可配合 C++11 的 chrono 使用的 high_resolution_timer  . steady_ ...

  10. cookie的基本用法

    1.创建cookie对象 Cookie newCookie=new Cookie(String ky,String value); 2.写入cookie response.addCookie(newC ...