【问题标题】:Printing f-strings in color in Jupyter with escape characters in the mix在 Jupyter 中以颜色打印 f 字符串,并在混合中使用转义字符
【发布时间】: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 字符串出现问题,这与printdisplay 的情况不同。那么我该如何解决呢?

【问题讨论】:

  • @hpaulj - 不,恐怕不能使用标签。
  • 如果您执行x=HTML(f...)(或Markdown),然后执行display(x),会发生什么情况。看看x.data
  • @hpaulj - 也试过这些 - 我能想到的任何组合;当你引入 HTML 或 Markdown 的那一刻——游戏就结束了。 x.data 是什么意思?
  • import htmlhtml.escape(tag)

标签: python string jupyter-notebook escaping ipython


【解决方案1】:

感谢@hpaulj(在问题的 cmets 中),我们现在有了一个不错且简单的答案 - 将 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>')))

输出:

简单有效...

【讨论】:

    猜你喜欢
    • 2016-05-29
    • 1970-01-01
    • 2015-05-27
    • 2021-12-26
    • 2022-12-24
    • 2020-02-28
    • 2016-05-10
    • 2016-03-18
    相关资源
    最近更新 更多