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

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

问题描述

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

 print("Hello Red World", color='red')

解决方案

当然,笔记本有自己的语法突出显示.所以我在其他地方使用颜色时会小心,只是为了避免让自己或其他人更难阅读(例如,输出应该只是黑色,但如果有例外,你会得到红色部分).

但是(出乎我的意料),您似乎可以使用 ANSI 转义码(即使在浏览器中).至少,我可以:

在默认的 Python 提示符下:

<预><代码>>>>打印("x1b[31m"红色"x1b[0m")红色的"

在笔记本中:

在[28]中:print("x1b[31m"red"x1b[0m")红色的"

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

我真的不知道另一种获得颜色的方法.

有关 ANSI 转义码的更多信息,我建议查看 维基百科文章.如果你发现上面的内容过于冗长,你当然可以围绕它编写一个包装函数.

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

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

On the default Python prompt:

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

In the notebook:

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

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

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天全站免登陆