
01
引言
在Python中我们最常使用的函数之一就是Print函数,使用该函数可以方便的打印各种中间变量,本文就Python中的Print函数相关技巧进行总结。
02
将输出写入文件中
假设我们已经完成了一个Python脚本,它可以打印一些内容到屏幕上,现在假设我们希望将打印的内容写入文本文件中,此时我们可以直接使用重定向操作。举例,假设我们有一个run.py,内容如下:
# run.pyprint("hello world")print(123)
如果我们直接运行该脚本,即使用python run.py ,此时上述代码将打印hello world 和 123 到屏幕上;但是我们也可以使用以下命令将输出重定向到文本文件中:
python run.py > out.txt
上述代码将正常运行run.py,同时上述脚本输出内容被重定向到文件out.txt中。
03
打印嵌套字典
假设我们的字典有多级,也就是我们有嵌套字典,举例如下:
d = {"apple": [{"recipe": "pie", "price":4},{"recipe": "juice", "price":5},{"recipe": "cake", "price":6},],"orange": [{"recipe": "pie", "price":14},{"recipe": "juice", "price":15},{"recipe": "cake", "price":16},],"pear": [{"recipe": "pie", "price":24},{"recipe": "juice", "price":25},{"recipe": "cake", "price":26},]}
如果我们需要查看上述字典的内容,我们直接使用print打印后输出如下:
{'apple': [{'recipe': 'pie', 'price': 4}, {'recipe': 'juice', 'price': 5}, {'recipe': 'cake', 'price': 6}], 'orange': [{'recipe': 'pie', 'price': 14}, {'recipe': 'juice', 'price': 15}, {'recipe': 'cake', 'price': 16}], 'pear': [{'recipe': 'pie', 'price': 24}, {'recipe': 'juice', 'price': 25}, {'recipe': 'cake', 'price': 26}]}
可以看出上述输出一团混乱,为了改善输出的可视化效果,我们可以使用pprint函数进行输出,样例代码如下:
from pprint import pprintpprint(d)
输出如下:
{'apple': [{'price': 4, 'recipe': 'pie'},{'price': 5, 'recipe': 'juice'},{'price': 6, 'recipe': 'cake'}],'orange': [{'price': 14, 'recipe': 'pie'},{'price': 15, 'recipe': 'juice'},{'price': 16, 'recipe': 'cake'}],'pear': [{'price': 24, 'recipe': 'pie'},{'price': 25, 'recipe': 'juice'},{'price': 26, 'recipe': 'cake'}]}
可以看出,上述输出明显变得更加直观易读。
04
打印彩色文本
在Python中为了打印彩色的文本,我们需要安装第三方库colorama,安装代码如下:
pip install colorama
用法如下:
from colorama import Foreprint(Fore.RED + "hello world")print(Fore.BLUE + "hello world")print(Fore.GREEN + "hello world")
输出如下:
05
总结
本文重点介绍了Python中最常用的Print函数的三个小技巧,可以帮助大家更好的可视化相应的调试信息,并给出了相应的代码示例!
您学废了吗?
点击上方小卡片关注我
万水千山总关情,点个在看行不行。

