问题
[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