LoginSignup
5
6

More than 5 years have passed since last update.

ユニコード文字列のリストの出力

Posted at

リストだとstr関数使おうとするので、
要素に対してprintするか、printするunicode型にformatで代入する。
要素の数が多くなると面倒だな・・・。

参考にしたサイト:
PythonのUnicodeEncodeErrorを知る

# -*- coding:utf-8 -*-
# 上記サイトででてくるデフォルト値を確認。
import sys, codecs
#なぜか次の行のやつが通らないことがある。versionの問題かな?#sys.stdout = codecs.EncodedFile(sys.stdout, 'utf_8')
sys.stdout = codecs.lookup(u'utf_8')[-1](sys.stdout)
print "sys.getdefaultencoding() => ",sys.getdefaultencoding()
print "sys.stdout.encoding => ",sys.stdout.encoding

# ここから、テスト

alist = [ u"ユニコード日本語", u"だよ"]

for st in alist :
    print st

print u"{0}{1}".format(*alist)

print map(str,alist)

以下は、出力。

sys.getdefaultencoding() =>  ascii
sys.stdout.encoding =>  UTF-8
ユニコード日本語
だよ
ユニコード日本語だよ
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    202             else:
    203                 filename = fname
--> 204             __builtin__.execfile(filename, *where)

/Users/yuuichi/test-print/test.py in <module>()
     15 print u"{0}{1}".format(*alist)
     16
---> 17 print map(str,alist)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6