我正在尝试使用 colorama
在Jupyter笔记本中,它没有任何作用。但在控制台中尝试时,它可以正常工作。这是我的示例代码。
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中尝试时,也出现了同样的问题。
你可以在这里使用一些标记符,使用 Markdown
和 display
来自 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"])
产出: