Wednesday, March 8, 2017

Is it possible to print using different color in ipython's Notebook?

Leave a Comment

Is it somehow possible to have certain output appear in a different color in the IPython Notebook? For example, something along the lines of:

 print("Hello Red World", color='red') 

4 Answers

Answers 1

The notebook has, of course, its own syntax highlighting. So I would be careful when using colour elsewhere, just to avoid making things harder to read for yourself or someone else (e.g., output should simply be in black, but you get parts in red if there is an exception).

But (to my surprise), it appears that you can use ANSI escape codes (even in the browser). At least, I could:

On the default Python prompt:

>>> print("\x1b[31m\"red\"\x1b[0m") "red" 

In the notebook:

In [28]: print("\x1b[31m\"red\"\x1b[0m")          "red" 

(Obviously, I cheated here with the syntax highlighting of SO so that "red" is printed in the colour red in both examples. I don't think SO allows a user to set a colour for text.)

I wouldn't really know another way to get colours.

For more on ANSI escape codes, I'd suggest the Wikipedia article. And if you find the above to verbose, you can of course write a wrapper function around this.

Answers 2

Not with raw Python print. You will have to define a _repr_html_ on an object and return it or call IPython.lib.display(object_with_repr_html).

I guess you could overwrite the built-in print to do it automatically...

You could inspire from http://nbviewer.ipython.org/5098827, code in a gist on github, ML discussion here.

Answers 3

you can use this library termcolor and you can get all other official libraries of python in pypi

See the documentation in pypi.python.org or follow these steps
1. pip install termcolor
2. then goto ipython
type

from termcolor import colored print colored('hello', 'red'), colored('world', 'green') print colored("hello red world", 'red') 

Output:

hello world hello red world 

The first argument is what you want to print on console and second argument use that color

Answers 4

Here's a quick hack:

from IPython.display import HTML as html_print  def cstr(s, color='black'):     return "<text style=color:{}>{}</text>".format(color, s)  left, word, right = 'foo' , 'abc' , 'bar' html_print(cstr(' '.join([left, cstr(word, color='red'), right]), color='black') ) 

[out]:

enter image description here

If you just want a single color: html_print(cstr('abc', 'red'))

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment