2019-08-13
How do I make python 3.7 print out colored text?
stackoverflow
Question

I am new to programming as a whole, however I have been able to write up a basic game in python. I have not been able to print colored text into the powershell on windows 10, it's cmd, or in the IDLE python came with. Although it does not crash my code, I would like my game to print out colored text, so i need to make a method that can do that.

def ColorText(text, color):
  CEND      = '\033[0m'
  CBOLD     = '\033[1m'
  CRED    = '\033[91m'
  CGREEN  = '\033[32m'
  CYELLOW = '\033[33m'
  CBLUE   = '\033[34m'
  CVIOLET = '\033[35m'
  CBEIGE  = '\033[36m'
  if color == 'red':
      return CRED + CBOLD + text + CEND
  elif color == 'green':
      return CGREEN + CBOLD + text + CEND
  elif color == 'yellow':
      return CYELLOW + CBOLD + text + CEND
  elif color == 'blue':
      return CBLUE + CBOLD + text + CEND
  elif color == 'voilet':
      return CVIOLET + CBOLD + text + CEND
  elif color == 'beige':
      return CBEIGE + CBOLD + text + CEND
Answer
1

You can print out coloured text in windows cmd like this(changes colour of whole cmd):

import os
os.system("color 3") # colour can be any number between 1 to 8
print("Your text")

Or you can use colorama like this:

from colorama import init, Fore, Back, Style
init(convert=True)
print(Fore.RED + 'some red text') 
print(Back.GREEN + 'and with a green background') 
print(Style.DIM + 'and in dim text') 
print(Style.RESET_ALL) 
print('back to normal now') 

You can read this article on GeeksForGeeks which shows how to change colours in terminals: https://www.geeksforgeeks.org/print-colors-python-terminal/

How do I make python 3.7 print out colored text?
See more ...