Frage

Is there any clean way to supress the unicode character prefix when printing an object using the pprint module?

>>> import pprint
>>> pprint.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'})
{u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'],
 u'foo': u'bar',
 u'hello': u'world'}

This looks pretty ugly. Is there any way to print the __str__ value of each object, instead of the __repr__?

War es hilfreich?

Lösung

It could be done by overriding the format method of the PrettyPrinter object, and casting any unicode object to string:

import pprint

def my_safe_repr(object, context, maxlevels, level):
    typ = pprint._type(object)
    if typ is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

printer = pprint.PrettyPrinter()
printer.format = my_safe_repr
printer.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'})

which gives:

{'baz': ['apple', 'orange', 'pear', 'guava', 'banana'],
 'foo': 'bar',
 'hello': 'world'}

Andere Tipps

This may be too much, but one possible way is to implement a wrapper over the output stream:

import pprint,sys,re

class writer :
    def write(self, text):
        text=re.sub(r'u\'([^\']*)\'', r'\1',text)
        sys.stdout.write(text)

wrt=writer()
d = { u'foo': u'bar', u'baz':
        [u'apple', u'orange', u'pear', u'guava', u'banana'],
        u'hello': u'world'}
pp = pprint.PrettyPrinter(stream=wrt)

pp.pprint(d)

Output:

{baz: [apple, orange, pear, guava, banana],
 foo: bar,
 hello: world}

It is also possible to put quotes inside parents to have single quotes around strings, e,g, 'foo' : 'bar':

text=re.sub(r'u(\'[^\']*\')', r'\1',text)

This gives:

{'baz': ['apple', 'orange', 'pear', 'guava', 'banana'],
 'foo': 'bar',
 'hello': 'world'}

No, pprint prints the representation. It's not for making pretty end-user output, but for printing Python objects in a readable way.

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.

(Many years later answer)

Just use python3. All standard strings are unicode by default, so no u prefix.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top