python-字符转换遇到的问题

时间:2014-08-27 18:10:38   收藏:0   阅读:198

1,异常: ‘ascii‘ codec can‘t encode characters

字符集的问题,在文件前加两句话:
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

2,unicode中的‘\xa0’字符在转换成gbk编码时会出现问题,gbk无法转换‘\xa0‘字符。

所以,在转换的时候必需进行一些前置动作:

string.replace(u‘\xa0‘, u‘ ‘)  

将‘\xa0‘替换成u‘ ‘空格。

3

 1 #! /usr/bin/env python
 2 #coding=utf-8
 3 s=raw_input()
 4 print s,type(s),len(s)
 5 s=s.decode("gbk")
 6 print s,type(s),len(s)
 7 s=s.encode("utf-8")
 8 print s,type(s),len(s)
 9 s="中国"
10 print s,type(s),len(s)

 

1 中国
2 中国 <type str> 4
3 中国 <type unicode> 2
4 中国 <type str> 6
5 中国 <type str> 6

raw_input读入是gbk编码的,汉字和字母都是

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!