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

后端 未结 12 1097
孤独总比滥情好
孤独总比滥情好 2020-12-23 09:15

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          


        
相关标签:
12条回答
  • 2020-12-23 09:56

    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.

    0 讨论(0)
  • 2020-12-23 09:58

    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]:

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

    0 讨论(0)
  • 2020-12-23 09:59

    You can use this library termcolor and you can get all other official libraries of python in PyPi.

    1. pip install termcolor
    2. then goto ipython

    Code

    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.

    See the documentation in pypi.python.org for more information

    0 讨论(0)
  • 2020-12-23 09:59

    There is the colored library (pip install colored), which you can use to modify a string to get color codes to modify how it is printed. Example use:

    import colored
    print(colored.bg("white") + colored.fg("red") + "Hello world!")
    
    0 讨论(0)
  • 2020-12-23 09:59

    Taken from: Standard for ANSI Colors in Terminals

    This snippet can show you all the colors in one row:

    RESET = "\x1b[0m"
    print("To reset attributes: \\x1b[0m\n")
    for i in range(0, 8):
        print("\x1b[1;3{0}m\\x1b[1;3{0}m{1} \x1b[0;3{0}m\\x1b[0;3{0}m{1} "
              "\x1b[1;4{0};3{0}m\\x1b[1;3{0};4{0}m{1}".format(i, RESET))
    
    0 讨论(0)
  • 2020-12-23 10:04

    In the Jupiter notebook, we can use a color marker to print the output in different colors There are three ways that we can use a color marker.

    let's see how to print a yellow color in a notebook.

    1. print('\033[93m output')
    2. print('\033[93m' 'output')
    3. print('\033[93m' + 'output')

    Some of the colors are :

    • yellow = '\033[93m'
    • green = '\033[92m'
    • red = '\033[91m'
    • blue = '\033[94m'
    • pink = '\033[95m'

    you can change the last number and get other colors as well.

    0 讨论(0)
提交回复
热议问题