Python受欢迎的原因之一就是其计算生态丰富,据不完全统计,Python 目前为止有约13万+的第三方库。
本系列将会陆续整理分享一些有趣、有用的第三方库。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/1FSGLd7aI_UQlCQuovVHc_Q?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_Ecosystem
pip install termcolor
termcolor主要包含colored()和cprint()两个函数,并支持文本颜色、背景色和样式的设置:
-
colored() 函数:
-
text: 要格式化的文本。 -
color: 文字颜色(如 ‘red’, ‘green’, ‘yellow’)。 -
on_color: 背景颜色(如 ‘on_red’, ‘on_blue’)。 -
attrs: 文本属性(如 [‘bold’, ‘underline’])。
from termcolor import colored
# 设置文本颜色
print(colored('这是红色文本', 'red'))
print(colored('这是绿色文本', 'green'))
# 设置背景颜色
print(colored('这是黄色背景的文本', 'white', 'on_yellow'))
# 设置文本样式
print(colored('这是高亮的红色文本', 'red', attrs=['bold']))
print(colored('这是闪烁的蓝色文本', 'blue', attrs=['blink']))
-
cprint() 函数:
from termcolor import cprint
cprint('这是绿色文本', 'green')
cprint('这是带有红色背景的文本', 'white', 'on_red')
cprint('这是加粗的黄色文本', 'yellow', attrs=['bold'])
-
支持的颜色和样式:

import colorama
colorama.init()
-
覆盖设置:
-
调用colored或cprint时,将no_color参数设置为真值,将禁用颜色。 -
调用colored或cprint时,将force_color参数设置为真值,将强制启用颜色。 -
将ANSI_COLORS_DISABLED环境变量设置为任意值,将禁用颜色。 -
将NO_COLOR环境变量设置为任意值,将禁用颜色。 -
将FORCE_COLOR环境变量设置为任意值,将强制启用颜色。 -
将TERM环境变量设置为dumb,或者使用此类“哑终端”,将禁用颜色。
以下是一些简单示例,展示了如何使用termcolor打印彩色和样式化的文本:
-
示例 1:
import sys
from termcolor import cprint
# 定义一个打印函数
print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan")
print_red_on_cyan("Hello, World!")
print_red_on_cyan("Hello, Universe!")
# 循环打印彩色文本
for i in range(10):
cprint(i, "magenta", end=" ")
# 打印到标准错误流
cprint("Attention!", "red", attrs=["bold"], file=sys.stderr)
输出效果:

-
示例 2:
from termcolor import colored
headers = ["Name", "Age", "Status"]
data = [
["Alice", 30, colored("Active", "green")],
["Bob", 25, colored("Inactive", "red")],
]
print(colored("{:<10} {:<5} {:<10}".format(*headers), "cyan"))
for row in data:
print("{:<10} {:<5} {:<10}".format(*row))
输出效果:

更多内容可以前往GitHub查看:
https://github.com/termcolor/termcolor


本篇文章来源于微信公众号: 码农设计师