Skip to content

Instantly share code, notes, and snippets.

@jlongster
Created January 31, 2011 16:46
Show Gist options
  • Save jlongster/804336 to your computer and use it in GitHub Desktop.
Save jlongster/804336 to your computer and use it in GitHub Desktop.
unicode printing
## test.py
key = u"things"
val = u"幾內亞比索"
print u"%s: %s" % (key, val)
## test2.py
from contextlib import closing
key = u"things"
val = u"幾內亞比索"
with closing(open("test.txt", "w")) as f:
# throws UnicodeEncodeError
f.write(u"%s: %s" % (key, val))
##
james:~/tmp% python test.py
things: 幾內亞比索
james:~/tmp% python test.py > test.txt
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "%s: %s" % (key, unicode(val))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-12: ordinal not in range(128)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment