Last active
December 15, 2015 16:29
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
got it
果然没这么用过