Making coloured Ascii text with Python

4.3k views Asked by At

I'm trying to make a title with coloured ascii for my code, which pops up when launching the code. I already know how to make ascii text but not coloured.

This is what I've been able to make, but now I want to have it in magenta.

result = pyfiglet.figlet_format("By Gxzs", font = "slant" )
print(result)

Ascii

I've already tried making it myself using colorama and termcolor, but I get a weird output :

title = pyfiglet.figlet_format(colored("By  Gxzs", color = "magenta"))
print(title)

Output

3

There are 3 answers

0
Breno Monteiro On

You can try it:

import pyfiglet as pyfiglet

def to_color(string, color):
    color_code = {'blue': '\033[34m',
                    'yellow': '\033[33m',
                    'green': '\033[32m',
                    'red': '\033[31m'
                    }
    return color_code[color] + str(string) + '\033[0m'

result = pyfiglet.figlet_format("By Gxzs", font = "slant" )

print(to_color(result,'blue'))

For more info information about ANSI Scape Codes and Color Codes click here

0
Diego Torres Milano On

You can use something like

af = 132
color = subprocess.run(['tput', 'setaf', f'{af}'], capture_output=True).stdout.decode('utf-8')
sgr0 = subprocess.run(['tput', 'sgr0'], capture_output=True).stdout.decode('utf-8')
print(f'{color}HELLO{sgr0}')

the values for the color (foreground in this case) can be seen using https://gist.github.com/dtmilano/4055d6df5b6e4ea87c5a72dc2d604193

0
john-hen On

A high-level library for "rich" text in the terminal is, well, rich. The colorama library that you mentioned is one of its dependencies.

To display the title in magenta, you would do this:

import pyfiglet
from rich import print

title = pyfiglet.figlet_format('By Gxzs', font='slant')
print(f'[magenta]{title}[/magenta]')