首页 > 解决方案 > 在 Jupyter 中以颜色打印 f 字符串,并在混合中使用转义字符

问题描述

我知道以前有人问过类似的问题,但我找不到任何确切的问题。假设我有这个列表:

tags = ['<div>','<body>','<h1>']

我可以在这里轻松地使用 f 字符串:

for tag in tags:
   print(f'this is your tag: {tag}')

输出:

this is your tag: <div>
this is your tag: <body>
this is your tag: <h1>

到现在为止还挺好。但我真正想做的是获得相同的输出,但标签名称打印为红色,例如红色。这就是我遇到括号问题的地方。如果我使用:

from IPython.display import HTML as html_print

for tag in tags:
     html_print(f'this is your tag: {tag}')

什么也没有打印出来——即使我删除了标签。

我试过:

from IPython.display import Markdown, display

然后首先:

for tag in tags:
   display(f'this is your tag: {tag}')

这就像一个普通的print.

但是,如果我尝试:

for tag in tags:    
   display(Markdown((f'this is your tag: {tag}')))

输出是:

this is your tag:
this is your tag:
this is your tag: 

我的理解是我需要Markdown用彩色打印,但显然括号会导致 f 字符串出现问题 in Markdown,这与使用printand的情况不同display。那么我该如何解决呢?

标签: pythonstringjupyter-notebookescapingipython

解决方案


感谢@hpaulj(在问题的评论中),我们现在有了一个不错且简单的答案 - 添加html.escape(tag)到代码中。最终阵容如下所示:

from IPython.display import Markdown, display
import html

for tag in tags:    
    tag = html.escape(tag)
    display(Markdown((f'this is your tag: <text style=color:red>{tag}</text>')))

输出:

在此处输入图像描述

简单有效...


推荐阅读