LoginSignup
3
3

More than 5 years have passed since last update.

print で、リスト内の非ascii文字を見栄え良く

Last updated at Posted at 2014-11-14

こんにちは。
リスト内の非ascii文字を見栄え良く print させる方法を、ここから見つけました:"How to print tuples of unicode strings in original language (not u'foo' form)"

s = [1, '日', ['本']]
print(list_str(s)) # ==> [1, '日', ['本']]
print(s) # ==> [1, '\xe6\x97\xa5', ['\xe6\x9c\xac']]
def list_str(x):
    if not isinstance(x, list):
        if isinstance(x, str):
            return '\'%s\'' % x
        return str(x)
    items = ', '.join([list_str(x) for x in x])
    return '[%s]' % items

また他に、
https://pypi.python.org/pypi/prettyprint の方法は、

import json
def list_str(x):
    return eval("u'''%s'''" % json.dumps(x)).encode('utf-8')

s = [1, '日', ['本']]
print(list_str(s)) # => [1, "日", ["本"]]
3
3
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
3
3