22

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?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Zex Xus
  • 221
  • 1
  • 2
  • 3
  • 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 Jun 19 '12 at 20:09
  • 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 Jun 19 '12 at 20:11
  • I've fixed the syntax of your code. – SomeKittens Jun 19 '12 at 20:12
  • indentation is still incorrect and I cant edit for whatever reason – Paul Seeb Jun 19 '12 at 20:19
  • @PaulSeeb: Lower reputation doesn't allow as many edit permissions. They need approvals. – jdi Jun 19 '12 at 20:24
  • Please just dont do this. Let the users choose the display colors that are most comfortable for them. – StingyJack Feb 05 '19 at 18:54
  • 2
    Possible duplicate of [How to print colored text in terminal in Python?](https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python) – Nazim Kerimbekov Apr 30 '19 at 21:39

8 Answers8

9

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.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
8

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

jdi
  • 90,542
  • 19
  • 167
  • 203
  • Will check this out,and come back with my results. Thanks a lot! – Zex Xus Jun 19 '12 at 20:15
  • Argh. Didn't work. i tried installing,by typing $ pip install ansicolors maybe i need to install this 'pip' i've never heard of pip before :P – Zex Xus Jun 19 '12 at 20:19
  • pip is the python package manager. If you don't have it already, try `easy_install pip` first – jdi Jun 19 '12 at 20:20
  • @ZexXus: I just saw you are using windows. This will be useless to you then. The windows command prompt won't print ansi colors – jdi Jun 19 '12 at 20:25
  • @ZexXus; I just added a link to help you – jdi Jun 19 '12 at 20:28
8

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

Hritik Jaiswal
  • 311
  • 3
  • 4
  • Windows doesn't understand ANSI codes. For example, I get `[0;30mHello world` outputted to the screen when I run the first hello world in Windows. – hostingutilities.com Oct 02 '20 at 17:26
  • You might be executing the code in python shell, but I think it only works in the terminal or in the editor, not in the shell. – Hritik Jaiswal Oct 03 '20 at 19:50
  • First Use `os.system('color')` to print colors to terminal – Mujtaba Sep 03 '22 at 07:33
  • 1
    @hostingutilities Of course Windows command prompt doesn't understand ANSI codes, but if you use Windows Terminal (which is awesome by itself) or PowerShell or pretty much any contemporary terminal - the colors are there. – Goujon Jul 17 '23 at 10:35
7

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.

Greg E.
  • 2,722
  • 1
  • 16
  • 22
5

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
3

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
math scat
  • 310
  • 8
  • 17
hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51
2

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

0

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.

Community
  • 1
  • 1
l4mpi
  • 5,103
  • 3
  • 34
  • 54
  • So i've gotta use Linux? Damnit. I preffer windows :( (not to say linux is bad) oh well. – Zex Xus Jun 19 '12 at 20:24
  • 1
    you could use [cygwin](http://cygwin.com) which basically gives you a linux shell and programs on a windows platform. I'd recommend it for programming under windows anyways because the cmd shell is just awful compared to bash. – l4mpi Jun 19 '12 at 20:30