下面的链接提供了一种在Jupyter笔记本代码单元中的python3print()
函数中呈现HTML URL的方法
https://github.com/jupyterlab/jupyterlab/issues/7393#issue-510053776
它定义了一个自定义URL类
"""URL Wrapper."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Url:
"""Wrapper around a URL string to provide nice display in IPython environments."""
__url: str
def _repr_html_(self):
"""HTML link to this URL."""
return f'<a href="{self.__url}">{self.__url}</a>' # problem here (*)
def __str__(self):
"""Return the underlying string."""
return self.__url
评论员指出,必须使用str(url())
来达到预期的结果
与(我认为)现在的内置呈现不同,我尝试使用这个自定义类:
linker = lambda my_string: str(Url('https://www.google.com/%s' % my_string))
print('URL for my_string is here',linker('search'))
我希望linker('search')
呈现为字符串“search”,后面是完整的超链接(https://www.google.com/search)。内置行为不会呈现“搜索”,而是呈现完整的超链接,我无法找到一种方法来成功修改自定义类来实现这一点。在上面的第(*)行,我尝试过:
return f'<a href="{self.__url}">{self.__url}</a>'
return f'<a href="{self.__url}">{"test_text"}</a>'
等等,但到目前为止都是徒劳的
这个答案有点帮助,但没有按照我的要求明确使用print函数:https://stackoverflow.com/a/43254984/1021819
我错过了什么
这有点僵硬,但似乎有效:
输出: 链接指向“https://www.google.com/search/hello/"
相关问题 更多 >
编程相关推荐