在 Jupyter 中打印彩色 f 字符串并混合使用转义字符

Jac*_*ing 0 python string escaping ipython jupyter-notebook

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

tags = ['<div>','<body>','<h1>']
Run Code Online (Sandbox Code Playgroud)

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

for tag in tags:
   print(f'this is your tag: {tag}')
Run Code Online (Sandbox Code Playgroud)

输出:

this is your tag: <div>
this is your tag: <body>
this is your tag: <h1>
Run Code Online (Sandbox Code Playgroud)

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

from IPython.display import HTML as html_print

for tag in tags:
     html_print(f'this is your tag: {tag}')
Run Code Online (Sandbox Code Playgroud)

即使我删除标签,也不会打印任何内容。

我试过:

from IPython.display import Markdown, display
Run Code Online (Sandbox Code Playgroud)

然后首先:

for tag in tags:
   display(f'this is your tag: {tag}')
Run Code Online (Sandbox Code Playgroud)

这就像常规操作一样print.

但是,如果我尝试:

for tag in tags:    
   display(Markdown((f'this is your tag: {tag}')))
Run Code Online (Sandbox Code Playgroud)

输出是:

this is your tag:
this is your tag:
this is your tag: 
Run Code Online (Sandbox Code Playgroud)

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

Jac*_*ing 5

感谢@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>')))
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

简单而有效...