-1

how could you create a print statement, such as print("Hello world") that could be a different colour (e.g. green).

Also, is there a way of doing this without needing to download new modules?

Samuel May
  • 65
  • 1
  • 10
  • 3
    Does this answer your question? [How to print colored text in terminal in Python?](https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python) – Brian61354270 Mar 08 '20 at 14:42
  • What is your beef with "external modules"? Most of them are just functions written in Python, so for a large part you can say "yes, that *is* possible without externals". Such modules do not add a layer of unknown magic to, say, sending plain ANSI escape codes to the console – which indeed you can do 'manually'. But why avoid them? – Jongware Mar 08 '20 at 17:40
  • If you are asking how to change colors in the system terminal/console, then the python-idle tag should be deleted. If you are asking how to change colors when running your code with IDLE and printing to its Shell, then there is a different duplicate, and the current official answer is that you cannot, so if you can, it will be limited and subject to change. – Terry Jan Reedy Mar 09 '20 at 03:13
  • @usr2564301 as I only have access to the default modules in school, and downloading new ones (such as pygame) is a pain, so avoiding them saves a lot of time. – Samuel May Mar 09 '20 at 19:26
  • @Brian this does not answer my question, sadly, as python 3.7.2 returns (in my case) `[7;30;40m 7;30;40 [0m[7;30;41m 7;30;41 [0m[7;30;42m 7;30;42 [0m[7;30;43m 7;30;43 [0m[7;30;44m 7;30;44 [0m[7;30;45m 7;30;45 [0m[7;30;46m 7;30;46 [0m[7;30;47m 7;30;47 [0m [7;31;40m 7;31;40 [0m[7;31;41m 7;31;41 [0m[7;31;42m 7;31;42 [0m[7;31;43m 7;31;43 [0m[7;31;44m 7;31;44 [0m[7;31;45m 7;31;45 [0m[7;31;46m 7;31;46 [0m[7;31;47m 7;31;47 [0m [7;32;40m 7;32;40 [0m[7;32;41m 7;32;41 [0m[7;32;42m 7;32;42 [0m[7;32;43m 7;32;43 [0m[7;32;44m 7;32;44 [0m[7;32;45m 7;32;45 ` – Samuel May Mar 09 '20 at 19:29
  • Perhaps you could benefit from the [Python curses library](https://docs.python.org/3/howto/curses.html) if that is available to you. – Scott Mar 10 '20 at 07:28
  • @epicgamer300065, did you run init() before running the print statements? Also, did you run this from command prompt (where it worked for me) or from IDLE or another IDE (where it produced resultant uncolored output like you posted)? – Scott Mar 10 '20 at 08:28
  • @Scott as I specified in the tags, I am trying to get this to work in python idle. – Samuel May Mar 11 '20 at 16:26

2 Answers2

1

@epicgamer300065, All of the following code was lifted from the links @Brian and I (@Scott) supplied earlier. I did need to insert an init() statement right after the imports to get the code to work, and I did need to run this from the command prompt (but admin privilege was not needed), but it does produce the expected, colored results. (FYI, I am using Python 3.8.1 on win10pro):

from colorama import init, Fore, Back, Style
from termcolor import colored 

init() 

print(Fore.RED + 'Test')

print(Fore.RED + Back.GREEN + 'some red text') 
print(Back.GREEN + 'and with a green background') 
print(Style.BRIGHT + 'and in bright text') 
print(Style.RESET_ALL) 
print('back to normal now')

print(colored('Hello, World!', 'green', 'on_red')) 


# Python program to print 
# colored text and background 
def prRed(skk): print("\033[91m {}\033[00m" .format(skk)) 
def prGreen(skk): print("\033[92m {}\033[00m" .format(skk)) 
def prYellow(skk): print("\033[93m {}\033[00m" .format(skk)) 
def prLightPurple(skk): print("\033[94m {}\033[00m" .format(skk)) 
def prPurple(skk): print("\033[95m {}\033[00m" .format(skk)) 
def prCyan(skk): print("\033[96m {}\033[00m" .format(skk)) 
def prLightGray(skk): print("\033[97m {}\033[00m" .format(skk)) 
def prBlack(skk): print("\033[98m {}\033[00m" .format(skk)) 

prCyan("Hello World, ") 
prYellow("It's") 
prGreen("Geeks") 
prRed("For") 
prGreen("Geeks") 

# Python program to print 
# colored text and background 
class colors: 
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg: 
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg: 
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

print(colors.bg.green + colors.fg.red, "SKk", colors.bg.blue + colors.fg.red, "Amartya") 
print(colors.bg.lightgrey, "SKk", colors.fg.red, "Amartya") 


# Python program to print 
# colored text and background 
def print_format_table(): 
    """ 
    prints table of formatted text format options 
    """
    for style in range(8): 
        for fg in range(30, 38): 
            s1 = '' 
            for bg in range(40, 48): 
                format = ';'.join([str(style), str(fg), str(bg)]) 
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format) 
            print(s1) 
        print('\n') 

print_format_table() 
Scott
  • 367
  • 1
  • 9
  • Thank you for your answer, but as I have explained before, I cannot install other modules that do not come default with python 3.7.2. colorama is one of them. – Samuel May Mar 11 '20 at 16:24
1

@epicgamer300065, here's an actual full IDLE solution that worked for me using Python 3.8.1 on win10pro, but it does NOT work in terminal.

It is from idlecolors and since your access is limited I have included the full module needed idlecolors.py herein for your copy/paste pleasure to circumvent your inability to install.

As you can see, the only dependencies are modules sys and random, but random is only needed for the randcol() function which you could live without if you had to.

Here's idlecolors.py:

import sys
import random

# This will only work in IDLE, it won't work from a command prompt
try:
    shell_connect = sys.stdout.shell
except AttributeError:
    print("idlecolors highlighting only works with IDLE")
    exit()

# Map the colour strings to IDLE highlighting
USE_CUSTOM_COLORS = False       # Change to True if you want to use custom colours

global colormap

if USE_CUSTOM_COLORS:
    colormap = {"red": "COMMENT",
                "orange": "KEYWORD",
                "green": "STRING",
                "blue": "stdout",
                "purple": "BUILTIN",
                "black": "SYNC",
                "brown": "console",

                "user1": "DEFINITION",
                "user2": "sel",
                "user3": "hit",
                "user4": "ERROR",
                "user5": "stderr"}
else:
    colormap = {"red": "COMMENT",
                "orange": "KEYWORD",
                "green": "STRING",
                "blue": "stdout",
                "purple": "BUILTIN",
                "black": "SYNC",
                "brown": "console"}

# ---------------------------
# Functions
# ---------------------------

# Like the print() function but will allow you to print colours
def printc(text, end="\n"):
    # Parse the text provided to find {text:color} and replace with the colour. Any text not encompassed in braces
    # will be printed as black by default.
    buff = ""
    for char in text:
        if char == "{":
            # Write current buffer in black and clear
            shell_connect.write(buff, colormap["black"])
            buff = ""
        elif char == "}":
            # Write current buffer in color specified and clear
            tag_write = buff.split(":")
            shell_connect.write(tag_write[0], tag_write[1])
            buff = ""
        else:
            # Add this char to the buffer
            buff += char

    # Write the chosen end character (defaults to newline like print)
    sys.stdout.write( end )


# Individual colour functions
def red(text):
    return "{"+ text + ":" + colormap["red"] + "}"

def orange(text):
    return "{"+ text  + ":" + colormap["orange"] + "}"

def green(text):
    return "{"+ text + ":" + colormap["green"] + "}"

def blue(text):
    return "{"+ text  + ":" + colormap["blue"] + "}"

def purple(text):
    return "{"+ text + ":" + colormap["purple"] + "}"

def black(text):
    return "{"+ text  + ":" + colormap["black"] + "}"

def brown(text):
    return "{"+ text + ":" + colormap["brown"] + "}"

def randcol(text):
    color = random.choice(list(colormap.keys()))
    return "{"+ text + ":" + colormap[color] + "}"

# User defined colours
def user1(text):
    return "{"+ text + ":" + colormap["user1"] + "}"

def user2(text):
    return "{"+ text + ":" + colormap["user2"] + "}"

def user3(text):
    return "{"+ text + ":" + colormap["user3"] + "}"

def user4(text):
    return "{"+ text + ":" + colormap["user4"] + "}"

def user5(text):
    return "{"+ text + ":" + colormap["user5"] + "}"

And here is how you would use it:

from idlecolors import *
printc( red("Red text") )
printc( "If you add " + red("red") + " to " + blue("blue") + ", you get " + purple("purple") )

# Print a line in a random colour
printc( randcol("This is a random colour") )

# Print each word in a random colour
mytext = "This is a random piece of text which I want to print in random colours"
mytext = mytext.split(" ")
for word in mytext:
    printc(randcol(word), end=" ")

The colors available are red(), orange(), green(), blue(), purple(), black(), brown(), and you can use randcol() for a random color from this selection.

Scott
  • 367
  • 1
  • 9