栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python通过2种方法输出带颜色字体

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python通过2种方法输出带颜色字体

方法1:

使用Python中自带的print输出带有颜色或者背景的字符串

书写语法

print(33[显示方式;前景色;背景色m输出内容33[0m)

其中,显示方式、前景色、背景色都是可选参数(可缺省一个或多个)。

参数

显示方式

显示方式 效果
0 默认
1 粗体
4 下划线
5 闪烁
7 反白显示

print("显示方式:")
print("33[0mSuixinBlog: https://suixinblog.cn33[0m")
print("33[1mSuixinBlog: https://suixinblog.cn33[0m")
print("33[4mSuixinBlog: https://suixinblog.cn33[0m")
print("33[5mSuixinBlog: https://suixinblog.cn33[0m")
print("33[7mSuixinBlog: https://suixinblog.cn33[0m")

颜色

字体色编号 背景色编号 颜色
30 40 黑色
31 41 红色
32 42 绿色
33 43 黄色
34 44 蓝色
35 45 紫色
36 46 青色
37 47 白色

print("字体色:")
print("33[30mSuixinBlog: https://suixinblog.cn33[0m")
print("33[31mSuixinBlog: https://suixinblog.cn33[0m")
print("33[32mSuixinBlog: https://suixinblog.cn33[0m")
print("33[4;33mSuixinBlog: https://suixinblog.cn33[0m")
print("33[34mSuixinBlog: https://suixinblog.cn33[0m")
print("33[1;35mSuixinBlog: https://suixinblog.cn33[0m")
print("33[4;36mSuixinBlog: https://suixinblog.cn33[0m")
print("33[37mSuixinBlog: https://suixinblog.cn33[0m")
print("背景色:")
print("33[1;37;40mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;41mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;42mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;43mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;44mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;45mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[37;46mtSuixinBlog: https://suixinblog.cn33[0m")
print("33[1;30;47mtSuixinBlog: https://suixinblog.cn33[0m")

方法2:

colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用。

1. 安装colorama模块

pip install colorama

可用格式常数:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

跨平台印刷彩色文本可以使用彩色光的常数简称ANSI转义序列:

from colorama import Fore,Back,Style
print (Fore.RED + "some red text")
print (Back.GREEN + "and with a green background")
print (Style.DIM + "and in dim text")
print (Style.RESET_ALL)
print ("back to normal now!!")

Init关键字参数:

init()接受一些* * kwargs覆盖缺省行为

init(autoreset = False):

如果你发现自己一再发送重置序列结束时关闭颜色变化每一个打印,然后init(autoreset = True)将自动化
示例:

from colorama import init,Fore
init(autoreset=True)
print (Fore.RED + "welcome to python !!")
print ("automatically back to default color again")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/20841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号