python print 輸出帶顏色字體

實現過程

終端的字符顏色是用轉義序列控制的,是文本模式下的系統顯示功能,和具體的語言無關html

轉義序列是以ESC開頭,即用\033來完成(ESC的ASCII碼用十進制表示是27,用八進制表示就是033)python

書寫格式code

開頭部分:\033[顯示方式;前景色;背景色m + 結尾部分:\033[0mhtm

注意:開頭部分的三個參數:顯示方式,前景色,背景色是可選參數,能夠只寫其中的某一個;另外因爲表示三個參數不一樣含義的數值都是惟一的沒有重複的,因此三個參數的書寫前後順序沒有固定要求,系統都能識別;可是,建議按照默認的格式規範書寫blog

對於結尾部分,其實也能夠省略,可是爲了書寫規範,建議\033[***開頭,\033[0m結尾get

數值表示的參數含義:string

顯示方式: 0(默認\)、1(高亮)、22(非粗體)、4(下劃線)、24(非下劃線)、 5(閃爍)、25(非閃爍)、7(反顯)、27(非反顯)class

前景色: 30(黑色)、31(紅色)、32(綠色)、 33(黃色)、34(藍色)、35(洋 紅)、36(青色)、37(白色)終端

背景色: 40(黑色)、41(紅色)、42(綠色)、 43(黃色)、44(藍色)、45(洋 紅)、46(青色)、47(白色)語言

懶人代碼示例(方便使用,即粘即用)

print("顯示方式:")
print("\033[0;37;40m--- Replace the string ---\033[0m")
print("\033[1;37;40m--- Replace the string ---\033[0m")
print("\033[22;37;40m--- Replace the string ---\033[0m")
print("\033[4;37;40m--- Replace the string ---\033[0m")
print("\033[24;37;40m--- Replace the string ---\033[0m")
print("\033[5;37;40m--- Replace the string ---\033[0m")
print("\033[25;37;40m--- Replace the string ---\033[0m")
print("\033[7;37;40m--- Replace the string ---\033[0m")
print("\033[27;37;40m--- Replace the string ---\033[0m")
print("前景色:")
print("\033[0;30;40m--- Replace the string ---\033[0m")
print("\033[0;31;40m--- Replace the string ---\033[0m")
print("\033[0;32;40m--- Replace the string ---\033[0m")
print("\033[0;33;40m--- Replace the string ---\033[0m")
print("\033[0;34;40m--- Replace the string ---\033[0m")
print("\033[0;35;40m--- Replace the string ---\033[0m")
print("\033[0;36;40m--- Replace the string ---\033[0m")
print("\033[0;37;40m--- Replace the string ---\033[0m")
print("背景色:")
print("\033[0;37;40m--- Replace the string ---\033[0m")
print("\033[0;37;41m--- Replace the string ---\033[0m")
print("\033[0;37;42m--- Replace the string ---\033[0m")
print("\033[0;37;43m--- Replace the string ---\033[0m")
print("\033[0;37;44m--- Replace the string ---\033[0m")
print("\033[0;37;45m--- Replace the string ---\033[0m")
print("\033[0;37;46m--- Replace the string ---\033[0m")
print("\033[0;37;47m--- Replace the string ---\033[0m")

由於隔一段時間不用就忘,這樣整一會兒用起來方便。

此處爲原博文傳送門, 支持正版

相關文章
相關標籤/搜索