Python:如何用彩色字体打印一行(含完整代码)
在Python中,我们可以用ANSI转义码来实现彩色字体的输出。本文将介绍如何使用Python打印一行彩色字体,代码也会一并提供。
首先,我们需要引入ANSI转义码,对应的颜色代码如下:
- 红色:\033[31m
- 绿色:\033[32m
- 黄色:\033[33m
- 蓝色:\033[34m
- 紫色:\033[35m
- 青色:\033[36m
我们可以通过向print()函数传递ANSI转义码和需要输出的文字,来实现彩色字体输出的效果。
下面是完整的源代码:
def print_color_text(color: str, text: str):
"""
打印彩色字体
:param color: 颜色代码
:param text: 输出文本
"""
print(f'{color}{text}\033[0m')
if __name__ == '__main__':
print_color_text("\033[31m", "这是红色字体")
print_color_text("\033[32m", "这是绿色字体")
print_color_text("\033[33m", "这是黄色字体")
print_color_text("\033[34m", "这是蓝色字体")
print_color_text("\033[35m", "这是紫色字体")
print_color_text("\033[36m", "这是青色字体")
我们可以在调用print_color_text()函数时指定颜色代码和需要输出的文本。其中,\033[0m用于重置颜色,保证其不影响后续输出。
通过这段代码,我们可以实现彩色字体的输出。你可以使用这个代码块打印出你在Python中所需的任何彩色字体。