python - 在同一行打印不同的元素,在 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 中尝试时会出现同样的问题
解决方案
你可以在这里使用一些降价,使用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"])
输出:
推荐阅读
- android - 如何防止约束视图中的 textView 离开屏幕
- angular - 如何解决角度示意图导航隐藏侧边栏的问题?
- javascript - 关闭表格折叠行
- c++ - 我需要将我的数组样式的邻接矩阵转换为矢量样式(使其看起来更好)
- c++ - 在 Linux 上使用 CMake 时,如何告诉 PVS-Studio 忽略第三方库中的所有文件
- androidx - Android - 导入 ViewPager2 库时程序类型已经存在 com.transition.R
- javascript - Modify properties of objects in array, based on string array
- javascript - 尝试将对象中的每个数字/值放入字符串数组
- java - 当我们将一个类变量分配给另一个类变量时,我们到底在做什么
- javascript - 为什么我不能读取我在 POST 中收到的参数?