Where/how does Jupyter notebook hook into python's repr/str

ぐ巨炮叔叔 提交于 2021-02-10 18:36:28

问题


[In jupyter notebook: python3 kernel]

If I make a data-frame in pandas or a matrix in sympy it prints very nicely ie it looks quite like a spreadsheet/matrix etc

How does it do it? Who does it?

The data-frame does not seem to have anything special (eg generating html) in the str/repr methods. Tried in ordinary python and jupyter. Jupyter's printing is much more sophisticated.

So where how does it hook in?


回答1:


I can only speak for pandas but I imagine sympy works in a similar way.

Pandas converts a DataFrame into an HTML string. If we print this string it it looks even worse than a when we just print a DataFrame.

from IPython.display import display, HTML
import pandas as pd

data = pd.DataFrame({'col': range(5)})

print(data._repr_html_())

'<div>\n<style scoped>\n    .dataframe tbody tr....'

If instead we use Jupyter's HTML to display this, Jupyter knows to render this in the web browser as HTML and thus is is displayed as an HTML table.

HTML(data._repr_html_())

    col
0   0
1   1
2   2
3   3
4   4


来源:https://stackoverflow.com/questions/48202162/where-how-does-jupyter-notebook-hook-into-pythons-repr-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!