How can I ouput a hyperlink with alternate text using python?

I am printing out a table using beautifultable, and it includes some urls, which would be great if I could reformat them to have shorter text. I would even like to use the markdown syntax, but it seems that the “Python Markdown” plugin doesn’t work with jupyter lab. Any other way to do something like this?

I have not used that plugin, but if I understood correctly then this does not require any plugin at all:

from IPython.display import Markdown

Markdown('[link name](https://example.com)')

Picture:

Screenshot from 2021-07-04 01-53-58

Is this what you were looking for, or did I misunderstood?

Edit: I missed the bit about beautifultable. In that case I would instead generate a proper markdown-formatted table (I don’t know if beautifultable can do it) and wrap it in display(Markdown(str(table))).

Edit 2: Apparently it can support markdown style with table.set_style(BeautifulTable.STYLE_MARKDOWN).

So this could look like:

from beautifultable import BeautifulTable
from IPython.display import Markdown


table = BeautifulTable()
table.rows.append(["[Jacob](https://example.com)", 1, "boy"])
table.rows.append(["Isabella", 1, "girl"])
table.columns.header = ["name", "rank", "gender"]
table.rows.header = ["S1", "S2"]
table.set_style(BeautifulTable.STYLE_MARKDOWN)

Markdown(str(table))

2 Likes

Works good, but I seem to have found a wierd problem. Seems there is something if the url is larger than a certain size the markdown isn’t formatted. Any ideas?

from beautifultable import BeautifulTable
from IPython.display import Markdown


table = BeautifulTable()
table.rows.append(["[Jacob](https://example.com/0123456789/0123456789/01234)", 1, "boy"])
table.rows.append(["[Isabe](https://example.com/0123456789/0123456789/0123)", 1, "gir"])
table.columns.header = ["name", "rank", "gender"]
table.rows.header = ["S1", "S2"]
table.set_style(BeautifulTable.STYLE_MARKDOWN)

Markdown(str(table))

1 Like

Yes, it seems that beautifultable is a bit aggressive with wrapping text into a next row if it exceeds a pre-specified length. From a quick look-up, you could use table = BeautifulTable(maxwidth=100) (or any higher number as needed) to work around this issue, tough you may also want to contact the beautifultable authors and ask them for their advice.

1 Like

Thanks, that worked again.

1 Like