Python的pprint模組中使用的格式化可以按照一種格式正確的顯示資料, 這種格式即可被解析器解析, 又很易讀. 輸出儲存在一個單行內, 但如果有必要, 在分割多行資料時也可使用縮排表示.
import sys import pprint pprint.pprint(sys.path)
執行結果:
['', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages']
如果僅僅想獲得資料而不是輸出資料也可以用pformat
import sys import pprint str = pprint.pformat(sys.path) print str
執行結果:
['', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages']
執行結果是一樣的~~