首页 > 编程语言 > 详细

python-字符转换遇到的问题

时间:2014-08-27 18:10:38      阅读:275      评论:0      收藏:0      [点我收藏+]

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编码的,汉字和字母都是

 

python-字符转换遇到的问题

原文:http://www.cnblogs.com/fkissx/p/3939675.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!