是否可以在ipython的Notebook中使用不同的颜色进行打印? [英] Is it possible to print using different colors in ipython's Notebook?

查看:98
本文介绍了是否可以在ipython的Notebook中使用不同的颜色进行打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在IPython Notebook中以某种不同的颜色显示某些输出? 例如,类似以下内容的东西:

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 Red World", color='red')

推荐答案

当然,笔记本具有自己的语法突出显示.因此,在其他地方使用颜色时,我会格外小心,以免使您自己或其他人难以理解(例如,输出应仅是黑色,但如果有例外,则部分显示为红色).

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).

但是(令我惊讶),看来您可以使用ANSI转义码(即使在浏览器中).至少,我可以:

But (to my surprise), it appears that you can use ANSI escape codes (even in the browser). At least, I could:

在默认的Python提示符下:

On the default Python prompt:

>>> print("\x1b[31m\"red\"\x1b[0m")
"red"

在笔记本电脑上:

In [28]: print("\x1b[31m\"red\"\x1b[0m")
         "red"

(显然,我在这里用SO的语法突出显示作弊,因此在两个示例中红色"都用红色打印.我不认为SO允许用户为文本设置颜色.)

(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.

有关ANSI转义代码的更多信息,建议您参阅 Wikipedia文章.而且,如果您发现上面的内容很冗长,则当然可以为此编写包装函数.

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.

这篇关于是否可以在ipython的Notebook中使用不同的颜色进行打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆