【发布时间】:2019-09-09 02:11:04
【问题描述】:
我知道以前有人问过类似的问题,但我找不到确切的答案。 假设我有这个列表:
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 进行彩色打印,但显然括号会导致Markdown 中的f 字符串出现问题,这与print 和display 的情况不同。那么我该如何解决呢?
【问题讨论】:
-
@hpaulj - 不,恐怕不能使用标签。
-
如果您执行
x=HTML(f...)(或Markdown),然后执行display(x),会发生什么情况。看看x.data。 -
@hpaulj - 也试过这些 - 我能想到的任何组合;当你引入 HTML 或 Markdown 的那一刻——游戏就结束了。
x.data是什么意思? -
import html和html.escape(tag)。
标签: python string jupyter-notebook escaping ipython