首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法编码/解码pprint输出

无法编码/解码pprint输出
EN

Stack Overflow用户
提问于 2012-06-04 14:55:40
回答 2查看 10.4K关注 0票数 18

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

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

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

代码语言:javascript
复制
HttpResponse(cy_content, content_type='text/plain; charset=utf-8')

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

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

代码语言:javascript
复制
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')

我的纯文本输出如下:

代码语言:javascript
复制
Here is the documentation part that contains Turkish chars like işüğçö

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

我试图解码或编码不同编码的pprint输出,但没有成功.克服这个问题的最佳做法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-04 15:28:41

默认情况下,pprint似乎使用repr,您可以通过重写PrettyPrinter.format来解决此问题。

代码语言:javascript
复制
# 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şüğçö}
票数 40
EN

Stack Overflow用户

发布于 2012-06-04 15:17:58

您应该使用unicode字符串而不是8位字符串:

代码语言:javascript
复制
API_STATUS = {
    1: u'müşteri',
    2: u'some other status message'
}

my_str = u'Here is the documentation part that contains Turkish chars like işüğçö'
my_str += pprint.pformat(API_STATUS, indent=4, width=1)

pprint模块旨在以可读的方式打印出所有可能的嵌套结构。要做到这一点,它将打印对象表示,而不是将其转换为字符串,因此您将以使用unicode字符串或不使用unicode字符串结束转义语法wheather。但是,如果您在文档中使用unicode,那么您确实应该使用unicode文本!

无论如何,thg435 has given you a solution如何改变pformat的这种行为。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10883399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档