使用 IPython.display.Code
高亮代码#
from IPython.display import Code
code = """
a = 12
b = 24
c = a + b
print(c)
"""
Code(code, language="python")
a = 12
b = 24
c = a + b
print(c)
也可以自定义高亮:
def code2html(code):
"""Helper function to use pygments to turn the code string into highlighted html."""
import pygments
from pygments.lexers import Python3Lexer
from pygments.formatters import HtmlFormatter
formatter = HtmlFormatter()
html = pygments.highlight(code, Python3Lexer(), formatter)
style = formatter.get_style_defs(".highlight")
return f"<style>{style}</style>\n{html}\n"
from IPython.display import HTML
HTML(code2html(code))
a = 12
b = 24
c = a + b
print(c)