python 令人抓狂的编码问题

#运行以下程序:
#! /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

  

 

posted @ 2016-04-03 18:50  蜗牛牛  阅读(172)  评论(0编辑  收藏  举报