How to print colored text in Python?

前端 未结 30 2922
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  借酒劲吻你
    2020-11-21 05:07

    Stupidly simple based on @joeld's answer

    class PrintInColor:
        RED = '\033[91m'
        GREEN = '\033[92m'
        YELLOW = '\033[93m'
        LIGHT_PURPLE = '\033[94m'
        PURPLE = '\033[95m'
        END = '\033[0m'
    
        @classmethod
        def red(cls, s, **kwargs):
            print(cls.RED + s + cls.END, **kwargs)
    
        @classmethod
        def green(cls, s, **kwargs):
            print(cls.GREEN + s + cls.END, **kwargs)
    
        @classmethod
        def yellow(cls, s, **kwargs):
            print(cls.YELLOW + s + cls.END, **kwargs)
    
        @classmethod
        def lightPurple(cls, s, **kwargs):
            print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
    
        @classmethod
        def purple(cls, s, **kwargs):
            print(cls.PURPLE + s + cls.END, **kwargs)
    

    Then just

    PrintInColor.red('hello', end=' ')
    PrintInColor.green('world')
    

提交回复
热议问题