Skip to content

Instantly share code, notes, and snippets.

@lexdene
Last active December 15, 2015 16:29
Show Gist options
  • Save lexdene/5289823 to your computer and use it in GitHub Desktop.
Save lexdene/5289823 to your computer and use it in GitHub Desktop.
Python的unicode函数似乎和sys.getdefaultencoding()有关。附: 《sys.setdefaultencoding is evil》http://ziade.org/2008/01/08/syssetdefaultencoding-is-evil/
# -*- coding: utf-8 -*-
a = '啦啦啦'
# an error will happen here
print '##### 1 #####'
try:
print unicode(a)
except Exception as e:
print 'error:'
print e
# explicit encoding
print '##### 2 #####'
a = '啦啦啦'
print unicode(a,'utf-8')
# time.strftime2
print '##### 3 #####'
import time
now = time.localtime()
timestr = time.strftime('%m月%d日',now)
print timestr
try:
print unicode(timestr)
except Exception as e:
print 'error:'
print e
print '##### 4 #####'
try:
timestr = time.strftime(u'%m月%d日',now)
except Exception as e:
print 'error:'
print e
# set default encoding
import sys
print sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
# everything ok.
print '##### 5 #####'
a = '啦啦啦'
print unicode(a)
print '##### 6 #####'
timestr = time.strftime('%m月%d日',now)
print timestr
print unicode(timestr)
print '##### 7 #####'
timestr = time.strftime(u'%m月%d日',now)
print timestr
@ggarlic
Copy link

ggarlic commented Apr 2, 2013

got it
果然没这么用过

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment