avatar Bite 324. Pretty string

Write a function that returns a neatly formatted string representation of a python object.

As you might have guessed, there is a package in the standard library that can help you with pretty printing and pretty formatting (pprint). This package can also be really useful for debugging with print statements.

The function pretty_str should pretty format the object with the following features:

 - Line breaks after items when 60 characters are reached

 - With nested items, only show items up to a depth of 2, otherwise display an ellipsis [...]

 - Dictionaries should be sorted according to their key order

>>> d={"Z": "Z"*40,
       "B": [1,[2,[3]]],
       "A": "A"*40}
>>> result = pretty_str(d)
>>> print(result)
{'A': 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
 'B': [1, [...]],
 'Z': 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'},
Login and get coding
go back Beginner level
Bitecoin 2X

42 out of 46 users completed this Bite.
Will you be Pythonista #43 to crack this Bite?
Resolution time: ~44 min. (avg. submissions of 5-240 min.)

We use Python 3.8