14
votes

New to both Python and StackOverflow, I'd like a little help. I'd like to print color in Python and have Googled but with little luck :( I've been confused each time and none has worked. This is the code I have typed.

answer = input ("Wanna go explore? OPTIONS : Yes or No")
if answer == "no":
    print("Awww, come on, don't be like that, lets go!")
elif answer == "yes":
    print ("Great! Lets go!")
else: 
    print("Whats that? I couldn't hear you!")

Now, I would like to have OPTIONS colored Green and Yes colored blue and No colored Red. How would one achieve this?

8
Your code is missing indentation and is syntactically invalid. You should fix that first. Also, I don't understand your requirements. What input would lead to what output? - phihag
Sorry. I didn't copy and paste the code directly,because you can't do that in IDLE,but it works fine in IDLE. Now,I want to make Options coloured green,Yes colored blue and No coloured red. Now,i'm new to python and no idea how to do this. Any idea? also,i apoligize if i didn't give you the answer you would have liked. I'll be honest,i don't quite understand what you mean at 'What output would lead to what output' - Zex Xus
I've fixed the syntax of your code. - SomeKittens
indentation is still incorrect and I cant edit for whatever reason - Paul Seeb

8 Answers

9
votes

If you want to print color in the IDLE shell no answer using ASCI escape codes will help you as it does not implement this feature.

There is a hack specific to IDLE that lets you write to it's PyShell object directly and specify text tags that IDLE has already defined such as "STRING" which will appear as green by default.

import sys

try:
    shell = sys.stdout.shell
except AttributeError:
    raise RuntimeError("you must run this program in IDLE")

shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")
answer = input()

When run in IDLE will result in this prompt:

enter image description here

Here is a list of all valid tags for use:

print("here are all the valid tags:\n")

valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
              'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')

for tag in valid_tags:
    shell.write(tag+"\n",tag)

Note that 'sel' is special that it represents the text that is selected, so it will be un-selected once something else is clicked on. As well it can be used to start some text selected for copying.

8
votes

If you just want a really simply and straightforward way to print ansi colors in the terminal you can check out the ansicolor package module:

Install via pip

$ pip install ansicolors

Usage snippet

from colors import red, green, blue
print red('This is red')
print green('This is green')
print blue('This is blue')

from colors import color
for i in range(256):
    print color('Color #%d' % i, fg=i)

Note about pip

pip is a python package manager. If you don't have pip installed, you can install it with easy_install pip

If you then find you don't have easy_install, then download this: http://peak.telecommunity.com/dist/ez_setup.py and do:

python ez_setup.py
easy_install pip

Colors for windows command shell

The above ansi colors will not work for you in a windows command shell. Try looking at this activestate code snippet

6
votes

If you're using a terminal and/or shell that support ANSI escape sequences, something like the following should work:

print("Blah blah \033[0;32mthis part will be green\033[00m blah blah.")
print("Blah blah \033[0;31mthis part will be red\033[00m blah blah.")

I can confirm that it does work in bash on Linux. See the Wikipedia page on ANSI escape codes for further details, including a comprehensive table describing the effects of different character sequences/values. I don't advocate this as a canonical solution, but it may be sufficient for your purposes.

5
votes

Check out the curses module. This will replace the print statements and give you complete control over the text positioning and attributes on your screen.

2
votes

I'd suggest this new library Printy which comes with an alternative function for both print() and input(). Just released version 1.2.0 as a cross-platform library.

It is based on flags so, for your case of use, you can do:

from printy import inputy
# with inline formats, this will apply a green(n)
# to the word 'OPTIONS', blue (b) to the word 'Yes', and red (r) to 
# the word No
inputy("Wanna go explore? [n]OPTIONS@ : [b]Yes@ or [r]No@")

enter image description here

you also can apply some validations, and the returned value would be already converted to boolean (or depending of the specified type)

enter image description here

It let you do more interesting things, Check it out: Printy on github

2
votes

Clint (Command Line INterface Tools) is a good library that I've used. It's a multipurpose library for anything to do with the terminal. There are functions in there for colors, yes/no prompts, progress bars, etc.

Using Clint for colored output looks like this:

>>> from clint.textui import colored, puts
>>> puts(colored.red('red text'))
red text
0
votes

If you want to print to a terminal in color you have to use escape codes for the terminal you're using. For unix/linux systems you can use the curses module - or just use bash color codes directly as a part of your output string. There doesn't seem to be an easy way to do this in windows according to this question.

0
votes

Colors in python

A simple method to print text nicely or style text using python, without any plugin or package.


# the ANSI codes are stored in variables, making them easier to use
black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
bright_black = "\033[0;90m"
bright_red = "\033[0;91m"
bright_green = "\033[0;92m"
bright_yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
bright_magenta = "\033[0;95m"
bright_cyan = "\033[0;96m"
bright_white = "\033[0;97m"

print(black + "Hello world")
print(red + "Hello world")
print(green + "Hello world")
print(blue + "Hello world")
print(yellow + "Hello world")
print(magenta + "Hello world")
print(cyan + "Hello world")
print(bright_black + "Hello world")
print(bright_red + "Hello world")
print(bright_green + "Hello world")
print(bright_blue + "Hello world")
print(bright_cyan + "Hello world")
print(bright_magenta + "Hello world")
print(bright_yellow + "Hello world")

output :

View : Colored output