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
相关推荐
脑袋大大的1 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
云泽野1 小时前
【Java|集合类】list遍历的6种方式
java·python·list
二进制person2 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6662 小时前
C++讲解---创建日期类
开发语言·c++·算法
IMPYLH3 小时前
Python 的内置函数 reversed
笔记·python
码农不惑3 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
Coding小公仔5 小时前
C++ bitset 模板类
开发语言·c++
小赖同学啊5 小时前
物联网数据安全区块链服务
开发语言·python·区块链
shimly1234565 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash