Home > Enterprise >  printing with RGB background
printing with RGB background

Time:12-30

I know its possible to print RGB colored text like so:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[39m".format(r, g, b, text)


text = "Hello, World"
colored_text = colored(132, 204, 247, text)
print(colored_text)

But, is there a way to print with RGB colored background?

Cuz, as far as I know, there are a few kinda built-in background colors for printing. But I want to be able to use rgb codes and get the appropriate background color for the printed text.

Is this possible?

Thanks.

CodePudding user response:

According to https://chrisyeh96.github.io/2020/03/28/terminal-colors.html#ansi-escape-codes-for-terminal-graphics the Select Graphic Rendition parameter following the '\033[' (the Control Sequence Inducer) to be used to define the background color is 48;2;r;g;b.

So here is colored_background that returns the text parameter with the given background color:

def colored_background(r, g, b, text):
    return f'\033[48;2;{r};{g};{b}m{text}\033[0m'

text = "What a nice red background!"
colored_text = colored_background(255, 0, 0, text)
print(colored_text)

You can naturally combine both:

def colored(fg_color, bg_color, text):
    r, g, b = fg_color
    result = f'\033[38;2;{r};{g};{b}m{text}'
    r, g, b = bg_color
    result = f'\033[48;2;{r};{g};{b}m{result}\033[0m'
    return result

text = "What a nice blue text with a red background!"
colored_text = colored((0, 0, 255), (255, 0, 0), text)
print(colored_text)

Note that here you only need one escape sequence with parameter 0 as this one resets both the foreground and the background colors to their default.

CodePudding user response:

I suggest using Curses module, it helps you to style apps running on command line.

Tech with Tim on YouTube has a tutorial for that. you'll find all what you need for coloring texts and backgrounds.

CodePudding user response:

this will do:

"\u001b[48;2;{};{};{}m{} \u001b[0m".format(r, g, b, text)

A helpful recourse I found:
https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#background-colors

  • Related