python输出带颜色的文字

方法一

示例代码:

python 复制代码
# ANSI escape codes for some colors
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
RESET = '\033[0m'  # Resets the color to default

print(f"{RED}This is red text{RESET}")
print(f"{GREEN}This is green text{RESET}")
print(f"{YELLOW}This is yellow text{RESET}")
print(f"{BLUE}This is blue text{RESET}")
print(f"{MAGENTA}This is magenta text{RESET}")
print(f"{CYAN}This is cyan text{RESET}")
print(f"{WHITE}This is white text{RESET}")

效果:

方法二

需要termcolor的支持

bash 复制代码
pip install colorama

示例代码:

python 复制代码
from colorama import Fore, Back, Style, init

# Initialize Colorama
init(autoreset=True)

print(Fore.RED + 'This is red text')
print(Fore.GREEN + 'This is green text')
print(Back.YELLOW + 'This has a yellow background')
print(Style.DIM + 'This is dim text')
print(Style.RESET_ALL)
print('Back to normal text')

效果:

方法三

需要termcolor:

bash 复制代码
pip install termcolor
python 复制代码
from termcolor import colored

print(colored('Hello, World!', 'red'))
print(colored('Green text', 'green'))
print(colored('Blue text', 'blue', 'on_white'))  # Blue text on white background
相关推荐
無限進步D3 小时前
Java 运行原理
java·开发语言·入门
是苏浙3 小时前
JDK17新增特性
java·开发语言
花酒锄作田5 小时前
企业微信机器人与 DeepAgents 集成实践
python·mcp·deepagents
阿里加多7 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood7 小时前
java中`==`和`.equals()`区别
java·开发语言·python
qq_283720057 小时前
Python Celery + FastAPI + Vue 全栈异步任务实战
vue.js·python·fastapi
2401_885885048 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
zs宝来了8 小时前
AQS详解
java·开发语言·jvm
telllong8 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
wjs202410 小时前
JavaScript 条件语句
开发语言