python - 无法编码/解码 pprint 输出

这个问题是基于 that one 的副作用。 .

我的 .py 文件在第一行都有 # -*- coding: utf-8 -*- 编码定义器,就像我的 api。 py

正如我在相关问题中提到的,我使用 HttpResponse 返回 api 文档。由于我通过以下方式定义编码:

HttpResponse(cy_content, content_type='text/plain; charset=utf-8')

一切正常,当我调用我的 API 服务时,除了 pprint 从字典中形成的字符串之外,没有任何编码问题

由于我在我的 dict 的某些值中使用土耳其语字符,pprint 将它们转换为 unichr 等价物,例如:

API_STATUS = {
    1: 'müşteri',
    2: 'some other status message'
}

my_str = 'Here is the documentation part that contains Turkish chars like işüğçö'
my_str += pprint.pformat(API_STATUS, indent=4, width=1)
return HttpRespopnse(my_str, content_type='text/plain; charset=utf-8')

而我的纯文本输出是这样的:

Here is the documentation part that contains Turkish chars like işüğçö

{
    1: 'm\xc3\xbc\xc5\x9fteri',
    2: 'some other status message'
}

我尝试将 pprint 输出解码或编码为不同的编码,但没有成功......克服这个问题的最佳实践是什么

最佳答案

pprint 默认使用 repr,您可以通过覆盖 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şüğçö}

https://stackoverflow.com/questions/10883399/

相关文章:

objective-c - 将 [NSDate date] 的日期缩短几个小时

java - 如何格式化具有大参数列表的方法

python - 并非所有参数都在字符串格式化期间转换

formatting - 如何在 Spring MVC 3.0 中显示格式化的 DateTime?

haskell - 如何让haskell输出不是科学计数法的数字?

excel - 如何防止自动截断 Excel 单元格中的前导零

r - 在 R 绘图图例中添加 pch 符号

python - 打印十六进制值时如何让 Python 使用大写字母?

asp.net-mvc - 使用 Razor View 引擎 - 如何将十进制值格式化为逗号和两位小

r - 自动格式化 R 代码的工具