Python rich – Print rainbow coloured text

In this post we will be creating a Python script that will print rainbow coloured text to output. To do this we will be using the ‘rich’ library which allows us to create aesthetically pleasing command line applications. The library is very useful whereby it allows formatting to many elements of output.

To install the rich library run the following command.

pip install rich

See the snippet of Python code below where we print rainbow coloured text. For this example we take a string as input from the user and then apply the ‘rainbow’ function before returning to output.

from random import randint
from rich import print
from rich.highlighter import Highlighter

class RainbowHighlighter(Highlighter):
    def highlight(self, text):
        for index in range(len(text)):
            text.stylize(f"color({randint(16, 255)})", index, index + 1)

rainbow = RainbowHighlighter()

while True:
    string=input("Enter Text: ")

An image of what this would look like whilst running can be seen below.

Python print Rainbow text using rich library,

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply