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
Similar to what @alvas mentioned but simpler
from IPython.display import Markdown
display (Markdown('this is in <span style="color: #ff0000">red</span> color.'))
colorama makes it dead easy:
from colorama import Fore
print(Fore.RED + "this is red")
Using @Evert answer, here is a method that would wrap a list of tokens in red and return a highlighted string
def color_in_tokens(tokens, color_token_contains="_"):
"""
Highlights the tokens which contain 'color_token_contains'
:param tokens: list of strings
:param color_token_contains: str (the string for marking a token red)
:return: str
"""
return " ".join(["\x1b[31m%s\x1b[0m" % i if color_token_contains in i else i for i in tokens])
Just call print on the returned string:
Text in red:
print("\x1b[31mText in red")
Text in bold:
print("\x1B[1mText in bold")
Text in underline
print("\x1B[4mText in underline")
See here under Styles and Colors chapter and see what works for you. RGB colors didn't work for me.
Thanks to @alvas function and adding another function we get a very simple way to print
from IPython.display import HTML as html_print
from IPython.display import display
def cstr(s, color='black'):
return "<text style=color:{}>{}</text>".format(color, s)
def print_color(t):
display(html_print(' '.join([cstr(ti, color=ci) for ti,ci in t])))
print_color((('hello my name is', 'black'),('jhjfd','red')))
print_color((('hello my name is', 'green'),))
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.