Printing Random Colored Text

Hi guys, I’m new to Python and I’m having trouble printing in random colors.

A few questions:
I know you can use code like this:

print("Uh, oh, you've been given a", "\33[31m", "warning", "\033[0m", "for being a bad, bad, person.")

In that case above the word warning would be in red, and this requires no other “imports” at the beginning.

Two questions:

  1. How do you randomize a color in that statement? Can you put a RGB value somehow in that section "\33[VariableName m", (?)

and have that variableName between 31-37.

  1. In the tutorials, the speakers shows a question prompt in 1 color, and then the input in another. I understand the color function in (1) above is only for “print” rather than “input”. Can you do it for input also?

  2. Basically I’m just looking for a better learning mechanism to understanding printing, inputs and randomizations with colors and everything I’m finding online is pretty confusing, involves library imports & complexity, and it’s just not simple.

Hopefully someone here can help.


Hey @alsonj, welcome to the forums!

Yeah, you can put RGB values like this:


The \033 is the escape code. the [38; makes it foreground, but you can use [48; for background instead. The R is the red component of your RGB, the G is your green component, and the B is the blue component.

See ANSI Color Specific RGB Sequence Bash - Stack Overflow for more information.

In the input prompt you can put a different color code like so:

input("\033[31mThis prompt is red\n> \033[34m")

If this answered your questions, please the post mark as a solution!


Hey, I found this very easy :

from termcolor import colored

print(colored("Hello world","red"))

This print Hello world in red


Yep! Thank you so much. That expanded on my knowledge and answered my question.

I also found a solution like this, although it’s probably not the best way to code. The import colored is probably better :slight_smile:

# colors
black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
bright_black = "\033[0;90m"
bright_red = "\033[0;91m"
bright_green = "\033[0;92m"
bright_yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
bright_magenta = "\033[0;95m"
bright_cyan = "\033[0;96m"
bright_white = "\033[0;97m"

print(bright_blue + "hello")
1 Like

Thanks so much! I’m assuming the termcolor & colored is similar coding to what I pasted below. That way seems easier :slight_smile:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.