Search code examples
pythonconsoleescapingansi-colors

How to color text more efficiently?


So I know how to color text, I am using a class to define colors and then using that in a print statements -

class color:
 purple = '\033[95m'
 cyan = '\033[96m'
 darkcyan = '\033[36m'
 blue = '\033[94m'
 green = '\033[92m'
 yellow = '\033[93m'
 end = '\033[0m'

print(color.green + This makes the text green! + color.end)

But I am working on a project for CSE class and there will lots of text to read, and eventually all the white just blends together, so using colored text makes things easier so I was wondering if there was an easier, less time consuming, way of doing things?


Solution

  • You could implement your own function that accepts the text and color, inserts the necessary codes, and prints. If you want to use a class, like you're doing, I'd recommend subclassing Enum, and naming the colors themselves in all caps, which is the Python convention for constants. (Also if you haven't seen f-strings before, I'd recommend giving them a look.)

    from enum import Enum
    
    class Color(Enum):
        PUPLE = 95
        CYAN = 96
        DARK_CYAN = 36
        BLUE = 94
        GREEN = 92
        YELLOW = 93
        # (Add any further colors you want to use...)
    
    def color_print(text, color):
        """Print text in the specified color."""
        if color not in Color:
            raise KeyError(f'Invalid text color: {color}')
        
        print(f'\033[{color.value}m{text}\033[0m')
    

    Which you can use like so:

    color_print('This text should be blue.', Color.BLUE)
    

    You could also accomplish the same thing with a dictionary. I'm not sure one method is any better or cleaner than the other, so you could pick whichever reads better to you and seems like it would be more convenient to use.

    COLORS = {
        'purple': 95,
        'cyan': 96,
        'dark_cyan': 36,
        'blue': 94,
        'green': 92,
        'yellow': 93,
        # (Add any further colors you want to use...)
    }
    
    def color_print(text, color):
        """Print text in the specified color."""
        try:
            code = COLORS[color]
        except KeyError:
            raise KeyError(f'Invalid text color: {color}')
        
        print(f'\033[{code}m{text}\033[0m')
    

    For this approach, you'd specify the color as a string rather than as a member of the Enum:

    color_print('This text should be blue.', 'blue')
    

    If you'd like a readymade solution, there's also the Rich package. It has an impressive list of capabilities, including but certainly not limited to printing in specified colors. Probably the simplest way to replicate the above in it would look like this:

    from rich.console import Console
    
    console = Console()
    console.print('This text shoudl be blue', style="blue")
    

    Rich can also do things like wrap and justify text, set foreground and background colors, make text blink, include emojis, and (perhaps most usefully, in my opinion) intelligently color-code data output with syntax highlighting right in the terminal. I just discovered this library myself, and I recommend giving it a look.