Python-如何在Python终端中打印彩色文本?

发布于 2021-02-02 23:23:55

如何用Python将彩色文本输出到终端?表示实心块的最佳Unicode符号是什么?

关注者
0
被浏览
253
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    我之所以做出回应,是因为我找到了一种在Windows上使用ANSI代码的方法,这样你就可以更改文本的颜色而无需任何内置模块:

    进行此操作的行是os.system('color'),但是要确保如果此人不在Windows上,则不会引起错误,你可以使用以下脚本:

    import os, sys
    
    if sys.platform.lower() == "win32":
        os.system('color')
    
    # Group of Different functions for different styles
    class style():
        BLACK = lambda x: '\033[30m' + str(x)
        RED = lambda x: '\033[31m' + str(x)
        GREEN = lambda x: '\033[32m' + str(x)
        YELLOW = lambda x: '\033[33m' + str(x)
        BLUE = lambda x: '\033[34m' + str(x)
        MAGENTA = lambda x: '\033[35m' + str(x)
        CYAN = lambda x: '\033[36m' + str(x)
        WHITE = lambda x: '\033[37m' + str(x)
        UNDERLINE = lambda x: '\033[4m' + str(x)
        RESET = lambda x: '\033[0m' + str(x)
    
    print(style.YELLOW("Hello, ") + style.RESET("World!"))
    

    注意:尽管此选项与其他Windows选项具有相同的选项,但是Windows即使使用此技巧也无法完全支持ANSI代码。并非所有的文本装饰颜色都起作用,并且所有“明亮”颜色(代码90-97和100-107)显示的颜色与常规颜色相同(代码30-37和40-47)

    tl; dr:os.system('color')在imports 之后添加。

    Python版本: 3.6.7



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看