码迷,mamicode.com
首页 > 编程语言 > 详细

python 令人抓狂的编码问题

时间:2016-04-03 20:13:15      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

#运行以下程序:
#! /usr/bin/env python
#coding=utf-8

file = open( ‘all_hanzi.txt‘,‘wb‘ )

listhz = []
n=0
for ch in xrange(0x4e00, 0x9fa6):
print unichr(ch),
file.write( unichr(ch) )#此行出错。正确:file.write( unichr(ch).encode(‘gbk‘))  encode(‘gbk‘)将‘utf-8’编码的string编码为‘gbk’
    n = n+1
if(n%50==0):
print ‘\n‘
file.write(‘\n‘)

print n
#报错:UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0-1: ordinal not in range(128)
#代码参考:http://www.cnblogs.com/mmix2009/p/3229787.html   python打印所有汉字

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312‘),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312‘),表示将unicode编码的字符串str2转换成gb2312编码

参考:http://www.cnblogs.com/bluescorpio/p/3594359.html

  

 

python 令人抓狂的编码问题

标签:

原文地址:http://www.cnblogs.com/woxinfeixiang2015/p/5350331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!