Unable to encode/decode pprint output

后端 未结 2 1840
闹比i
闹比i 2020-12-03 07:38

This question is based on a side-effect of that one.

My .py files are all have # -*- coding: utf-8 -*- encoding definer on the first line,

2条回答
  •  再見小時候
    2020-12-03 08:16

    pprint appears to use repr by default, you can work around this by overriding PrettyPrinter.format:

    # coding=utf8
    
    import pprint
    
    class MyPrettyPrinter(pprint.PrettyPrinter):
        def format(self, object, context, maxlevels, level):
            if isinstance(object, unicode):
                return (object.encode('utf8'), True, False)
            return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
    
    
    d = {'foo': u'işüğçö'}
    
    pprint.pprint(d)              # {'foo': u'i\u015f\xfc\u011f\xe7\xf6'}
    MyPrettyPrinter().pprint(d)   # {'foo': işüğçö}
    

提交回复
热议问题