Rabarberski Rabarberski -4 years ago 98
Python Question

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

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')

Answer Source

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")

In the notebook:

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

(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download