Disallow unicode prefix for strings when using pprint

Is there any clean way to suppress 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'} 

It looks pretty ugly. Is there a way to print the __str__ value of each object instead of __repr __?

+4
source share
3 answers

This can be done by overriding the format method of the PrettyPrinter object and selecting any unicode object in the 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'} 
+9
source

It may be too much, but one of the possible ways 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} 

You can also 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'} 
+2
source

No, pprint prints the view. This is not for creating a pretty end user, but for printing Python objects in a readable way.

The pprint module provides the ability to "print" optionally a Python Data Structure in a form that can be used as input to a translator.

+1
source

Source: https://habr.com/ru/post/1484104/


All Articles