Python Printing Readable Results
There are different ways to print readable results in Python depending on what kind of data you have. For example:
If you have a complex data structure such as a nested dictionary or list, you can use pprint module to format it nicely with indentation and line breaks. For example:
import pprint
data = {"name": "Alice", "age": 25, "hobbies": ["reading", "coding", "gaming"]}
pprint.pprint(data)
# Output:
{'age': 25,
'hobbies': ['reading', 'coding', 'gaming'],
'name': 'Alice'}
If you have a numerical data such as a matrix or an array, you can use numpy module to print it with precision and alignment. For example:
import numpy as np
matrix = np.array([[1.2345, 2.3456], [3.4567, 4.5678]])
np.set_printoptions(precision=2)
print(matrix)
# Output:
[[1.23 2.35]
[3.46 4.57]]
If you have a text data such as a string or a paragraph, you can use f-strings to format it with placeholders and expressions. For example:
name = "Bob"
age = 30
message = f"Hello, {name}. You are {age} years old."
print(message)
# Output:
Hello, Bob. You are 30 years old.
The normal print statement works fine in most situations but when the output is in the form of tables, JSON, or contains multiple results then you have to add some functionality to it or use some external package.
# pprint (pretty print)
from pprint import pprint
import json
f = open('data.json',)
data = json.load(f)
pprint(data)
f.close()
# Output
{'glossary':
{'GlossDiv':
{'GlossDef':
{'GlossSeeAlso': ['GML', 'XML'],'para': 'A meta-markup language, used '
'to create markup languages ''such as DocBook.'},
'GlossSee': 'markup'},
'title': 'example glossary'}}
# Normal Print
import json
f = open('data.json',)
data = json.load(f)
print(data)
f.close()
# Output
{'glossary': {'title': 'example glossary', 'GlossDiv': {'GlossDef': {'para': 'A meta-markup language, used to create markup languages such as DocBook.', 'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment