Python2 字符串编码
2016-05-23 22:59
465 查看
python2 中默认是ascii编码,对程序外读取的汉字需要解码为Unicode字符串进行处理。
python2中从程序外读取字符,通过decode解码为Unicode字符,使用encode将Unicode字符转化为指定的编码输出。
使用chartdet获取字符的编码
有时我们不一定知道已有字符的编码格式,可以使用chardet模块来获取字符的编码。chardet不是Python自带的模块,需要安装。
python2中从程序外读取字符,通过decode解码为Unicode字符,使用encode将Unicode字符转化为指定的编码输出。
>>> s = '你好呀' # 解码为Unicode字符, 编码格式不一定为utf-8,要看读入字符具体的格式 >>> s1 = s.decode('utf-8') # 将Unicode字符编码为gbk格式的字符 >>> s2 = s1.encode('gbk') >>> s1 u'\u4f60\u597d\u5440' >>> s2 '\xc4\xe3\xba\xc3\xd1\xbd'
使用chartdet获取字符的编码
有时我们不一定知道已有字符的编码格式,可以使用chardet模块来获取字符的编码。chardet不是Python自带的模块,需要安装。
>>> import chardet >>> s = '你好呀' >>> en_type = chardet.detect(s)['encoding'] >>> s.decode(en_type) u'\u4f60\u597d\u5440' >>> chardet.detect(s) {'confidence': 0.87625, 'encoding': 'utf-8'}
相关文章推荐
- Python学习笔记(二)在线用pip下载第三方包
- python
- python正则学习总结
- Python -- 字符串 列表 元组 字典
- 基于Python的接口测试框架
- leetcode 318. Maximum Product of Word Lengths-最长单词积|位运算
- Python程序-打印九九乘法表
- python的socket解决死锁的几个方法
- python中isort的使用
- python 以16进制打印输出
- LeetCode Max Points on a Line
- Python之路_Day3
- Python Numpy.ndarray ValueError:assignment destination is read-only
- python写计算器
- python的类
- python的文件操作方法
- python中内置函数locals()和gloabls()解析
- Python写的嗅探器——Pyside,Scapy
- venv pip install mysql-python问题
- python正则表达式(二)