Search code examples
pythoncolorsansi-escape

ANSI Color Escape Sequences Different Foreground and Background color with 256 colors


I'm using the ANSI Escape Sequence codes to add color to terminal output in my program.

I am mainly using this code, where COLOR can be any value between 0 and 255 to achieve great color variation.

\033[38;5;COLOR;1m TEXT \u001b[0m

The problem is that using the 256 color spectrum I am unable to have the "background" (7m) be colored with the string in the foreground being colored as well.

Using this format I am able to have the background and foreground have their own colors, but I am no longer able to use 256 colors, being reverted to 8 or so...

\x1b[1;32;41m Green On Red \x1b[0m"

After extensive testing with values and formats, I have not found a way to have separately colored background and foreground with the 256 color spectrum. Is there a way to do this?


Solution

  • Managed to figure it out!

    I simply run the escape sequence twice before the text. Once for background color, once for foreground color.

    \033[48;5;(ONE OF 256 COLORS)m\033[38;5;(ONE OF 256 COLORS)m TEXTHERE \033[0;0m
    

    This allows me to use the whole 256-color spectrum in both BG and FG, no imports or addons needed.