Python มีความสามารถในการจัดรูปแบบเนื้อหาของคำสั่ง print ให้เหมาะสมโดยใช้เมธอดพิเศษที่เรียกว่า pretty print หรือ pprint ตัวอย่างเช่นเมื่อเราอ่านเนื้อหาของ URL ที่อยู่ในรูปแบบ JSON เนื้อหาจะถูกพิมพ์เป็นบรรทัดเดียวซึ่งอ่านหรือเข้าใจยาก แต่ถ้าเราใช้ pretty print Python จะให้โครงสร้างที่สวยงามตามแท็ก JSON
ไม่ใช้ pprint
ในโปรแกรมด้านล่างเราพิมพ์เนื้อหา JSON ของเพจเว็บโดยใช้คำสั่ง print แบบดั้งเดิม ผลลัพธ์ทั้งหมดจะมาออกมาเป็นบรรทัดเดียว
ตัวอย่าง
import requests json_url_link = "https://pypi.org/pypi/sampleproject/json" result = requests.get(json_url_link) print(result.json())
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลดังนี้ −
{'info': {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', ...
ใช้ pprint
ต่อไปเราใช้เนื้อหาเดียวกันกับข้างต้นแต่ใช้ pprint แทน ตามที่เห็นรูปแบบผลลัพธ์มีการจัดระเบียบอย่างเป็นระบบมาก
ตัวอย่าง
import requests from pprint import pprint json_url_link = "https://pypi.org/pypi/sampleproject/json" result = requests.get(json_url_link) pprint(result.json())
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลดังนี้ −
{'info': {'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'bugtrack_url': None,
'classifiers': ['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',