How To Print Coloured Text In A Terminal

impshum(43)
Published in
#python
Words
141
Reading
1 min
Listen
Play
7y

86r8lGZ.jpg

Print Simple Colours With Python



There's other solutions out there like coloured but this little class does me nicely.

class C:
    W, G, R, P, Y, C = '\033[0m', '\033[92m', '\033[91m', '\033[95m', '\033[93m', '\033[36m'



Let's take it for a spin.

print(f'I like the colours {C.Y}green, {C.P}red, {C.R}purple, {C.C}cyan {C.W}and {C.G}yellow{C.W}')



Woo!

RFMert9.png



Watch out as you have to close with {C.W} to change back to white as there's no default... just change.

UPDATE



It does not work right out of the box with windows, to get the colours to work (on windows 10) you need to do the following...

  • Open Regedit
  • Go to HKEY_CURRENT_USER>Console
  • Create a DWORD with VirtualTerminalLevel
  • Set the value to 1


    If you have any open cmd or powershell windows close them and reopen them and poof... colours.


    Thanks for reading. x

Resources

How To Print Coloured Text In A Terminal | Ecency