How to make every character/line print in a random color?

Viewed 2902

My wish is to make every character or line or whatever you think might look best for an ASCII to look. Basically I have tried colorama and it was only based on one color. What is the best method?

What I have is

print("""


   _____ _             _                        __ _
  / ____| |           | |                      / _| |
 | (___ | |_ __ _  ___| | _______   _____ _ __| |_| | _____      __
  \___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__|  _| |/ _ \ \ /\ / /
  ____) | || (_| | (__|   < (_) \ V /  __/ |  | | | | (_) \ V  V /
 |_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_|  |_| |_|\___/ \_/\_/




    """)

and that is pretty much it. Let me know your thoughts through this!

1 Answers

The valid foreground colors provided by colorama are variables on colorama.Fore. We can retrieve them using vars(colorama.Fore).values(). We can random select a foreground color by using random.choice, feeding it the foreground colors as obtained by vars.

Then we simply apply a randomly-chosen color to each character:

text = """   


   _____ _             _                        __ _               
  / ____| |           | |                      / _| |              
 | (___ | |_ __ _  ___| | _______   _____ _ __| |_| | _____      __
  \___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__|  _| |/ _ \ \ /\ / /
  ____) | || (_| | (__|   < (_) \ V /  __/ |  | | | | (_) \ V  V / 
 |_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_|  |_| |_|\___/ \_/\_/  




    """

import colorama
import random

colors = list(vars(colorama.Fore).values())
colored_chars = [random.choice(colors) + char for char in text]

print(''.join(colored_chars))

This will print every character in a different color:

color characters

If you want colored lines instead, it's a simple change:

colored_lines = [random.choice(colors) + line for line in text.split('\n')]
print('\n'.join(colored_lines))

enter image description here

You can tailor the list of colors to your needs. For instance, if you want to remove colors which may be similar to your terminal background (black, white, etc.) you can write:

bad_colors = ['BLACK', 'WHITE', 'LIGHTBLACK_EX', 'RESET']
codes = vars(colorama.Fore)
colors = [codes[color] for color in codes if color not in bad_colors]
colored_chars = [random.choice(colors) + char for char in text]

print(''.join(colored_chars))

Which gives:

enter image description here

Related