首页 > 解决方案 > 在同一行打印不同的元素,在 Jupyter Notebook 中使用不同的颜色

问题描述

我正在尝试colorama在 Jupyter notebook 中使用,但它什么也没做。但是,当在控制台中尝试它时,它工作正常。这是我的示例代码:

from sys import stdout
from colorama import Fore

# Option 1
stdout.write(Fore.RED + "Test")

# Option 2
print(Fore.GREEN + "Test")

我的目标是在同一行以不同的颜色打印不同的元素。

我在 Linux (Ubuntu 20) 上并使用 Python 2.7。当我在 python3 中尝试时会出现同样的问题

标签: pythonjupyter-notebook

解决方案


你可以在这里使用一些降价,使用Markdowndisplay来自IPython.display模块。

我相信这个答案可能是您正在寻找的。


编辑

根据您在评论中提到的问题答案,这里有一些代码在同一行打印不同的元素,颜色相同

In [1]:     class ListOfColoredStrings(object):
                def __init__(self, *args):
                    """
                    Expected input:
                    args = ["word_1", "color_1"], ["word_2", "color_2"]

                    :param args: pairs of [word, color], both given as strings
                    """
                    self.strings = [a[0] for a in args]
                    self.colors = [a[1] for a in args]

                def _repr_html_(self):
                    return ''.join( [
                       "<span class='listofstr' style='color:{}'>{}</span>"
                            .format(self.colors[i], self.strings[i])
                       for i in range(len(self.strings))
                       ])

In [2]:     %%html
            <style type='text/css'>
            span.listofstr {
              margin-left: 5px
            }
            </style>

In [3]:     ListOfColoredStrings(["hi", "red"], ["hello", "green"])

输出:

输出


推荐阅读