0

I know that similar questions were asked before, but I couldn't find anything exactly on point. Say I have this list:

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

I can easily use f-strings here:

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

Output:

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

So far so good. But I am really trying to do, is get the same output but with the tag names printed in, for example, red. And this is where I run into problems with the brackets. If I use:

from IPython.display import HTML as html_print

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

nothing prints out - even if I remove the tags.

I tried:

from IPython.display import Markdown, display

And then first:

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

That works like a regular print.

If, however, I try:

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

The output is:

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

My understanding is that I need Markdown to print in color, but obviously the brackets are causing problems with the f-strings in Markdown, unlike the case with print and display. So how do I get around that?

Jack Fleeting
  • 20,849
  • 6
  • 20
  • 43

1 Answers1

5

Thanks to @hpaulj (in the comments to the question) we now have a nice and simple answer - add html.escape(tag) to the code. The final lineup looks like this:

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

Output:

enter image description here

Simple and effective...

Jack Fleeting
  • 20,849
  • 6
  • 20
  • 43